Office 2013 shared

 Copy code hover
[image]

Office 2013 shared
Send feedback

Published: July 16, 2012

Explore the links below to find out more about how to develop solutions for Office 2013.

Explore Office 2013 developer resources

New features and scenarios

New features

What's new for Office 2013 developers

Get started

Get started

Build apps for Office

Getting Started with VBA in Office 2010

References

Reference

Integrating IM applications with Office

Office Telemetry Log

Object library reference for Office 2013

Visual Basic for Applications language reference for Office 2013

Open XML SDK 2.5 CTP for Office

Find training and other resources about Office

Email us to suggest content Subscribe to the Office developer RSS Read Office developer blogs Read Office developer forums Visit MSDN Office and SharePoint on Facebook Follow @MSDN_Office on Twitter

Download

Office updates

Office 365

Office code samples

Office scripts and sample files

Office downloads

Office 365 downloads

How To

Train Office 2010 end users

Office developer videos

Office IT pro training

Office IT pro videos

Sites

Office 365 IT pros

Office 2013 Resource Kit

SharePoint developers

SharePoint IT pros

Office.com

Microsoft.com: Office 365

Additional resources

  • Access 2013

  • Excel 2013

  • InfoPath 2013

  • OneNote 2013

  • Outlook 2013

  • PowerPoint 2013

  • Project 2013

  • Publisher 2013

  • SharePoint 2013

  • Visio 2013

  • Word 2013

© 2013 Microsoft Corporation. All rights reserved.


Integrating IM applications with Office

 Copy code hover
[image]

Integrating IM applications with Office
Send feedback

Published: December 18, 2012

This article describes how to configure an instant message (IM) client application so that it integrates with the social features in Office 2013, including displaying presence and sending instant messages from the contact card.

Applies to: Word 2013 | Excel 2013 | PowerPoint 2013 | Outlook 2013 | Visio 2013 | Project 2013 | OneNote 2013 | SharePoint Server 2013 | Lync 2013

In this article
Introduction
How Office integrates with an IM client application
Setting registry keys and entries
Implementing the required interfaces for integration with Office
Implementing contact presence integration
Additional resources

If you have any questions or comments about this technical article or the processes that it describes, you can contact Microsoft directly by sending an email to docthis@microsoft.com.

Introduction

Office 2013 provides rich integration with IM client applications, including Lync 2013. This integration provides users with IM capabilities from within Word 2013, Excel 2013, PowerPoint 2013, Outlook 2013, Visio 2013, Project 2013, and OneNote 2013 as well as providing presence integration on SharePoint 2013 pages. Users can see the photo, name, presence status, and contact data for people in their contacts list. They can start an IM session, video call, or phone call directly from the contact card (the UI element in Office 2013 that surfaces contact information and communication options). Office 2013 makes it easy to stay connected to your contacts without taking you outside of your email or documents.

Note Note

This article uses the term IM client application to refer specifically to the application installed on a user's computer that communicates to the IM service. For example, Lync 2013 is considered an IM client application. This article does not provide details about how the IM client application communicates to the IM service or about the IM service itself.

You can customize an IM client application so that it communicates with Office. Specifically, you can modify your IM application so that it displays the following information within the Office UI:

  • Contact photo.

  • Contact name.

  • Contact personal status note.

  • Contact presence status.

  • Contact availability string (for example, "Available" or "Out of Office").

  • Contact capability string (for example, "Video Ready").

  • One-click IM launch.

  • One-click video call launch.

  • One-click phone call launch (including SIP, phone number, voice mail, and call new number).

  • Contact management (add to IM group).

  • Contact location and time zone.

  • Contact data, phone number, email address, title, and company name.

Figure 1. Contact card in Office 2013

The People Card in Office 2013

To enable this integration with Office, an IM client application must implement a set of interfaces that Office provides to connect to it. The APIs for this integration are included in the UCCollborationLib namespace that is contained in the Microsoft.Office.UC.dll file, which is installed with certain versions of Office 2013. The UCCollaborationLib namespace includes the interfaces that you must implement to integrate with Office.

Note Note

A handful of Office 2010 applications can integrate similarly with a third-party IM provider application: Outlook 2010, Word 2010, Excel 2010, PowerPoint 2010, and SharePoint Server 2010 (using an ActiveX control). Many of the steps required for integration with Office 2013 apply to Office 2010 as well.

There are several key differences in how Office 2010 integrates with an IM provider application:

  • Office 2010 does not display the contact's photo.

  • You must download the Microsoft.Office.Uc.dll file separately from Office 2010. The Lync 2010 SDK includes the Microsoft.Office.UC.dll file for Office 2010.

  • When the Office application calls the IUCOfficeIntegration.GetAuthenticationInfo method on the IM client application, it passes in the string "14.0.0.0".

  • Office 2010 enumerates all groups and contacts as soon as it connects to an IM client application.

How Office integrates with an IM client application

When an Office 2013 application starts, it goes through the following process to integrate with the default IM client application:

  1. It checks the registry to discover the default IM client application and then connects to it.

  2. It authenticates with the IM client application.

  3. It connects to specific interfaces that are exposed by the IM client application.

  4. It determines the capabilities of the currently signed-in user (local user), including getting the user's contacts, determining the user's presence, and determining the user's IM capabilities (instant messaging, video chat, VOIP, and so on).

  5. It gets presence information for the local user's contacts.

  6. When the IM client application shuts down, the Office 2013 application silently disconnects.

Discovering the IM application

The Office application looks for several specific keys and entries in the registry to discover the default IM client application. If it discovers a default IM client application, it then attempts to connect to it.

The process that the Office application goes through to discover the default IM client application is as follows:

  1. The Office application looks to see if the HKEY_CURRENT_USER\Software\IM Providers\DefaultIMApp subkey in the registry is set and reads the application name listed there.

  2. The Office application then reads the HKEY_CURRENT_USER\Software\IM Providers\Application name\UpAndRunning key and monitors the value for changes.

  3. The Office application next reads the HKEY_LOCAL_MACHINE\Software\IM Providers\Application name registry key and gets the ProcessName and class ID (CLSID) values stored there.

  4. Once the IM client application has completed its start sequence successfully and registered all of the classes correctly for the presence integration, it sets the HKEY_CURRENT_USER\Software\IM Providers\Application name\UpAndRunning key to "2", indicating that the client application is running.

  5. When the Office application discovers that the HKEY_CURRENT_USER\Software\IM Providers\Application name\UpAndRunning key has been set to "2", it checks the list of running processes on the computer for the process name of the IM client application.

  6. Once the Office application finds the process that the IM client application uses, the Office application calls CoCreateInstance using the CLSID to establish a connection to the IM client application as an out-of-process COM server.

Authenticating the connection to the IM application

After the Office application establishes a connection to the IM client application, it then does the following:

  1. The Office application calls IUnknown::QueryInterface method to check for the IUCOfficeIntegration interface.

  2. The Office application then calls the IUCOfficeIntegration.GetAuthenticationInfo method, passing in the highest supported integration version (for example, "15.0.0.0").

  3. If the IM client application supports the version of Office passed in as a parameter, the application returns the following hard-coded XML string to the calling code:

    <authenticationinfo>

    Note Note

    For legacy reasons, the IM client application must return the exact value <authenticationinfo> to the call to GetAuthenticationInfo if it supports the version of Office passed in as a parameter.

  4. If the IM client application fails to return a value, the Office application calls the GetAuthenticationInfo method again with the next highest supported version of Office (for example, "14.0.0.0").

  5. Once Office determines that the IM client application supports IM and presence integration, it connects to a required set of interfaces to finish initializing. (For more information, see Connecting to required interfaces.)

If the Office application encounters an error on any of the steps above, it backs out and presence integration is not established again during the session of the Office application.

Connecting to required interfaces

After authenticating the connection to the IM client application, the Office application attempts to connect to a set of required interfaces that the IM client application must expose. The Office application accomplishes this by doing the following:

  • The Office application gets an ILyncClient object by calling the IUCOfficeIntegration.GetInterface method, passing in the oiInterfaceLyncClient constant from the UCCollaborationLib.OIInterface enumeration.

  • The Office application gets an IAutomation object by calling the IUCOfficeIntegration.GetInterface method, passing in the oiInterfaceAutomation constant from the OIInterface enumeration.

  • The Office application sets up the _ILyncClientEvents event listener.

  • The Office application sets up the _IUCOfficeIntegrationEvents event listener.

  • The Office application gets the sign-in state from the IM client application by accessing the ILyncClient.State property.

  • The Office application gets the capabilities of the IM client application by calling the IUCOfficeIntegration.GetSupportedFeatures method, which returns a flag from the UCCollaborationLib.OIFeature enumeration.

  • The Office application accesses the ILyncClient.Self property to get a reference to an ISelf object.

Retrieving the capabilities of the local user

The Office application gets the capabilities of the local user by doing the following:

  1. If the IM client application supports the IClient2 interface, Office tries to get an IContactManager object by accessing the IClient2.PrivateContactManager property.

  2. If the IM application does not support the IClient2 interface, Office application gets an IContactManager object by accessing the ILyncClient.ContactManager property. The IM client application must successfully return an IContactManager object before any other IM capabilities can be established.

  3. The Office application accesses the ILyncClient.Uri property and then calls IContactManager.GetContactByUri to get the IContact object associated with the local user.

  4. The Office application then makes several calls to IContact.CanStart to establish the capabilities of the local user, passing in the values for ModalityTypes.ucModalityInstantMessage and ModalityTypes.ucModalityAudioVideo successively.

Retrieving contact presence

The Office application gets contact presence, including the local user, by doing the following:

  1. The Office application calls IContact.GetContactInformation to get a presence item from the contact.

  2. The Office application then subscribes to presence status changes from the contact. It calls IContactManager.CreateSubscription to get an IContactSubscription object. It then calls IContactSubscription.AddContact to add the contact to the subscription and then calls IContactSubscription.Subscribe to get changes in the contact's status.

  3. If the IM application supports IContact2, Office attempts to get presence information by calling IContact2.BatchGetContactInformation2.

  4. The Office application then retrieves the presence properties for the contact by calling IContact.BatchGetContactInformation. The Office application can get a second set of presence properties by accessing the IContact.Settings property.

  5. Finally, the Office application gets the contact's group membership by accessing the IContact.CustomGroups property. This returns an IGroupCollection collection that includes all of the IGroup objects that the contact belongs to.

Disconnecting from the IM application

When the Office 2013 application detects the OnShuttingDown event from the IM application, it disconnects silently. However, if the Office application shuts down before the IM application, the Office application does not guarantee that the connection is cleaned up. The IM application must handle client connection leaks.

Setting registry keys and entries

As mentioned previously, the IM-capable Office 2013 applications look for specific keys, entries, and values in the registry to discover the IM client application to connect to. These registry values provide the Office application with the process name and CLSID of the class that acts as the entry point to the IM client application's object model (that is, the class that implements the IUCOfficeIntegration interface). The Office application co-creates that class and connects as a client to the out-of-process COM server in the IM client application.

Use Table 1 to identify the keys, entries, and values that must be written in the registry to integrate an IM client application with Office.

Table 1. Registry keys for setting the default IM client application

Key

Entry

Type

Value

Example

HKEY_LOCAL_MACHINE\Software\IM Providers\<Application name>

FriendlyName

REG_SZ

The name of the third-party IM client application.

Litware IM 2012

ProcessName

REG_SZ

The process name of the third-party IM client application.

litware.exe

GUID

REG_SZ

A class ID (CLSID) for the root, cocreatable class in the IM application (the class that implements the IUCOfficeIntegration interface).

(A GUID)

HKEY_CURRENT_USER\Software\IM Providers

DefaultIMApp

REG_SZ

The name of the IM client application. This must be the same as the name at the top-level registry key (hive) in the HKEY_LOCAL_MACHINE.

Litware

HKEY_CURRENT_USER\Software\IM Providers\<Application name>

UpAndRunning

REG_DWORD

An integer value between 0 and 2:

  • 0—Not running

  • 1—Starting

  • 2—Running

Note Note

The application name registry key must be the same as the value of the DefaultIMApp entry.

Implementing the required interfaces for integration with Office

There are three interfaces from the UCCollaborationLib namespace that the executable (or COM server) of an IM client application must implement so that it can integrate with Office. If these interfaces are not implemented, the Office application backs out during the initialization process and the connection with the IM client application is not established.

The required interfaces are as follows:

  • IUCOfficeIntegration—Although not required, the _IUCOfficeIntegrationEvents interface should also be implemented in the same derived class.

  • ILyncClient—Although not required, the _ILyncClientEvents interface should also be implemented in the same derived class.

  • IAutomation

IUCOfficeIntegration interface

The IUCOfficeIntegration interface provides the entry-point for an Office application to connect to the IM client application. The interface defines three methods that an Office application calls as part of the process of initiating a connection with the IM client application. The class that implements the IUCOfficeIntegration interface must be co-creatable so that Office can co-create an instance of it. In addition, it must expose the CLSID that is entered as the value for the GUID entry in the HKEY_LOCAL_MACHINE\Software\IM Providers\Application name registry key.

The class that inherits from IUCOfficeIntegration should also implement the _IUCOfficeIntegrationEvents interface. The _IUCOfficeIntegrationEvents interface contains the members that expose the event handlers of the IUCOfficeIntegration interface.

Table 2 shows the members that must be implemented in the class that inherits from IUCOfficeIntegration and _IUCOfficeIntegration.

Note Note

For more information about the IUCOfficeIntegration and _IUCOfficeIntegrationEvents interfaces and their members, see UCCollaborationLib.IUCOfficeIntegration and UCCollaborationLib._IUCOfficeIntegrationEvents.

Table 2. Implementation of the IUCOfficeIntegration and _IUCOfficeIntegrationEvents interfaces
Interface | Member | Description
IUCOfficeIntegration | GetAuthenticationInfo method | Gets the authentication info string.
 | GetInterface method | Gets the interface of a particular version.
 | GetSupportedFeatures method | Gets the supported Office integration features.
_IUCOfficeIntegrationEvents | OnShuttingDown event | The event raised when the IM client application is trying to shut down.

Use the following code to define a class that inherits from the IUCOfficeIntegration and _IUCOfficeIntegration interfaces within an IM client application.

C# Copy code Copy code
// An example of a class that can be co-created and can integrate
// with Office as an IM provider.
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(_IUCOfficeIntegrationEvents))]
[Guid("{CLSID value}"), ComVisible(true)]
public class LitwareClientAppObject : IUCOfficeIntegration
{
    // Implementation details omitted.
}

The GetAuthenticationInfo method takes a string as an argument for the version parameter. When the Office application calls this method, it passes in one of two strings for the argument, depending on the version of Office. When the Office application supplies the method with the version of Office that the IM client application supports (that is, supports the functionality), the GetAuthenticationInfo method returns a hard-coded XML string "<authenticationinfo>".

Use the following code to implement the GetAuthentication method within the IM client application code.

C# Copy code Copy code
public string GetAuthenticationInfo(string _version)
{
    // Define the version of Office that the IM client application supports.
    string supportedOfficeVersion = "15.0.0.0";

    // Do a simple check for equivalency.
    if (supportedOfficeVersion == _version)
    {

        // If the version of Office is supported, this method must
        // return the string literal "<authenticationinfo>" exactly.
        return "<authenticationinfo>";
    }
    else
    {
        return null;
    }
}

The GetInterface method shuttles references to classes to the calling code, depending on what is passed in as an argument for the interface parameter. When an Office application calls the GetInterface method, it passes in one of two values for the interface parameter: either the oiInterfaceILyncClient constant (1) or the oiInterfaceIAutomation constant (2) of the UCCollaborationLib.OIInterface enumeration. If the Office application passes in the oiInterfaceILyncClient constant, the GetInterface method returns a reference to a class that implements the ILyncClient interface. If the Office application passes in the oiInterfaceIAutomation constant, the GetInterface method returns a class that implements the IAutomation interface.

Use the following code example to implement the GetInterface method within the IM client application code.

C# Copy code Copy code
public object GetInterface(string _version, OIInterface _interface)
{

    // These objects implement the ILyncClient or IAutomation
    // interfaces respectively. There is no restriction on what these
    // classes are named.
    IMClient imClient = new IMClient();
    IMClientAutomation imAutomation = new IMClientAutomation();

    // Return different object references depending on the value passed in
    // for the _interface parameter.
    switch (_interface)
    {
        // The calling code is asking for an object that inherits
        // from ILyncClient, so it returns such an object.
        case OIInterface.oiInterfaceILyncClient:
        {
            return imClient;
        }
        // The calling code is asking for an object that inherits
        // from IAutomation, so it returns such an object.
        case OIInterface.oiInterfaceIAutomation:
        {
            return imAutomation;
        }
        default:
        {
            throw new NotImplementedException();
        }
    }
}

The GetSupportedFeatures method returns information about the IM features that the IM client application supports. It takes a string for its only parameter, version. When the Office application calls the GetSupportFeatures method, the method returns a value from the UCCollaborationLib.OIFeature enumeration. The returned value specifies the capabilities of the IM client, where each capability of the IM client application is indicated to the Office application by adding a flag to the value.

Note Note

Office 2013 applications ignore the following constants in the OIFeature enumeration:

  • oiFeaturePictures (2)

  • oiFeatureFreeBusyIntegration

  • oiFeaturePhoneNormalization

Use the following code example to implement the GetSupportFeatures method within the IM client application code.

C# Copy code Copy code
public OIFeature GetSupportedFeatures(string _version)
{
    OIFeature supportedFeature1 = OIFeature.oiFeatureQuickContacts;
    OIFeature supportedFeature2 = OIFeature.oiFeatureFastSearch;

    return (supportedFeature1 | supportedFeature2);
}

ILyncClient interface

The ILyncClient interface maps to the capabilities of the IM client application itself. It exposes properties that refer to the person who is signed into the application (the local user, represented by the UCCollaborationLib.ISelf interface), the state of the application, the list of contacts for the local user, and several other settings. When it's trying to connect to the IM client application, the Office application gets a reference to an object that implements the ILyncClient interface. From that reference, Office can access much of the functionality of the IM client application.

In addition, the class that implements the ILyncClient interface should also implement the _ILyncClientEvents interface. The _ILyncClientEvents interface exposes several of the events that are required for monitoring the state of the IM client application.

Table 3 shows the members that must be implemented in the class that inherits from ILyncClient and _ILyncClientEvents.

Note Note

Any member of the ILyncClient or _ILyncClientEvents interface not listed in the table must be present but does not need to be implemented. Members that are present but not implemented can throw a NotImplementedException or E_NOTIMPL error.

For more information about the ILyncClient and _ILyncClientEvents interfaces and their members, see UCCollaborationLib.ILyncClient and UCCollaborationLib._ILyncClientEvents.

Table 3. Implementation of ILyncClient and ILyncClientEvents interfaces
Interface | Member | Description
ILyncClient | ContactManager property | Gets the contact group manager.
 | ConversationManager property | Gets the conversations manager.
 | Self property | Gets the Self object.
 | SignIn method | Starts the IM client application sign-in process with a specific availability.
 | State property | Gets the current platform state.
 | Uri property | Gets the URI of the IM client application.
_ILyncClientEvents | OnStateChanged event | Raised when the IM client application state changes. You should handle this event and get the eventData.NewState property. The event is raised for all processes bound to an instance of an IM client application when any subsystem in the application causes the state change.

During the initialization process, Office accesses the ILyncClient.State property. This property needs to return a value from the UCCollaborationLib.ClientState enumeration.

C# Copy code Copy code
private ClientState _clientState;
public ClientState State
{
    get
    {
        return this._clientState;
    }
}

The State property stores the current status of the IM client application. It must be set and updated throughout the IM client application session. When the IM client application signs in, signs out, or shuts down, it should set the State property. It is best to set this property within the ILyncClient.SignIn and ILyncClient.SignOut methods, as the following example demonstrates.

C# Copy code Copy code
// This field is of a type that implements the
// IAsynchronousOperation interface.
private IMClientAsyncOperation _asyncOperation = new IMClientAsyncOperation();

// This field is of a type that implements the ISelf interface.
private IMClientSelf _self;

public IMClientAsyncOperation SignIn(string _userUri, string _domainAndUser,
    string _password, object _IMClientCallback, object _state)
{
    ClientState _previousClientState = this._clientState;
    this._clientState = ClientState.ucClientStateSignedIn;

    // The IMClientStateChangedEventData class implements the
    // IClientStateChangedEventData interface.
    IMClientStateChangedEventData eventData =
        new IMClientStateChangedEventData(_previousClientState,
        this._clientState);

    if (_userUri != null)
    {
        // During the sign-in process, create a new contact with
        // the contact information of the currently signed-in user.
        this._self = new IMClientSelf(IMContact.BuildContact(_userUri));
    }

    // Raise the _ILyncClientEvents.OnStateChanged event.
    OnStateChanged(this, eventData as UC.ClientStateChangedEventData);

    return this._asyncOperation;
    }
}

IAutomation interface

The IAutomation interface automates features of the IM client application. It can be used to start conversations, join conferences, and provide extensibility window context.

Table 4 shows the members that must be implemented in the class that inherits from IAutomation.

Note Note

Any member of the IAutomation interface not listed in the table must be present but does not need to be implemented. Members that are present but not implemented can throw a NotImplementedException or E_NOTIMPL error.

For more information about the IAutomation interface and its members, see UCCollaborationLib.IAutomation.

Table 4. Implementation of IAutomation interface
Member | Description
StartConversation method | Starts a conversation using the specified conversation modality. An instance of IConversationWindow is returned.

Implementing contact presence integration

In addition to the three required interfaces discussed previously, there are several other interfaces that are important for enabling contact presence functionality in Office. These include the following:

  • The IContact or IContact2 interface.

  • The ISelf interface.

  • The IContactManager and _IContactManagerEvents interfaces.

  • The IGroup and IGroupCollection interfaces.

  • The IContactSubscription interface.

  • The IContactEndPoint interface.

  • The ILocaleString interface

IContact interface

The IContact interface represents an IM client application user. The interface exposes presence, available modalities, group membership, and contact type properties for a user. To start a conversation with another user, you must provide that user instance of IContact.

Table 5 shows the members that must be implemented in the class that inherits from IContact.

Note Note

Any member of the IContact interface not listed in the table must be present but does not need to be implemented. Members that are present but not implemented can throw a NotImplementedException or E_NOTIMPL error.

For more information about the IContact interface and its members, see UCCollaborationLib.IContact.

Table 5. Implementation of the IContact interface
Member | Description
CanStart method | Returns true if a given type of modality can be started on the contact.
GetContactInformation method | Gets one presence item from a publishing contact.
BatchGetContactInformation method | Gets multiple presence items from a publishing contact.
Settings property | Gets a collection of contact properties.
CustomGroups property | Gets a collection of groups that the contact is a member of.

During the initialization process, the Office application calls the IContact.CanStart method to determine the IM capabilities for the local user. The CanStart method takes a flag from the UCCollaborationLib.ModalityTypes enumeration as an argument for the _modalityTypes parameter. If the current user can engage in the requested modality (that is, the user is capable of instant messaging, audio and video messaging, or application sharing), the CanStart method returns true.

C# Copy code Copy code
public bool CanStart(ModalityTypes _modalityTypes)
{
    // Define the capabilities of the current IM client application
    // user by using flags from the ModalityTypes enumeration.
    ModalityTypes userCapabilities =
        ModalityTypes.ucModalityInstantMessage |
        ModalityTypes.ucModalityAudioVideo |
        ModalityTypes.ucModalityAppSharing;

    // Perform a simple test for equivalency.
    if (_modalityType == userCapabilities)
    {
        return true;
    }
    else
    {
        return false;
    }
}

The GetContactInformation method retrieves information about the contact from the IContact object. The calling code needs to pass in a value from the UCCollaborationLib.ContactInformationType enumeration for the _contactInformationType parameter, which indicates the data to be retrieved.

C# Copy code Copy code
public object GetContactInformation(
    ContactInformationType _contactInformationType)
{

    // Determine the information to return from the contact's data based
    // on the value passed in for the _contactInformationType parameter.
    switch (_contactInformationType)
    {
        case ContactInformationType.ucPresenceEmailAddresses:
        {

            // Return the URI associated with the contact.
            string returnValue = this.Uri.ToLower().Replace("sip:", String.Empty);
            return returnValue;
        }
        case ContactInformationType.ucPresenceDisplayName:
        {

            // Return the display name associated with the contact.
            string returnValue = this._DisplayName;
            return returnValue;
        }
        default:
        {
            throw new NotImplementedException;
        }
        // Additional implementation details omitted.
    }
}

Similar to the GetContactInformation, the BatchGetContactInformation method retrieves multiple presence items about the contact from the IContact object. The calling code needs to pass in an array of values from the ContactInformationType enumeration for the _contactInformationTypes parameter. The method returns an UCCollaborationLib.IContactInformationDictionary object that contains the requested data.

C# Copy code Copy code
public IMClientContactInformationDictionary BatchGetContactInformation(
    ContactInformationType[] _contactInformationTypes)
{

    // The IMClientContactInformationDictionary class implements the
    // IContactInformationDictionary interface.
    IMClientContactInformationDictionary contactDictionary =
        new IMClientContactInformationDictionary();

    foreach (ContactInformationType type in _contactInformationTypes)
    {
        // Call GetContactInformation for each type of contact
        // information to retrieve. This code adds a new entry to
        // a Dictionary object exposed by the
        // ContactInformationDictionary property.
        contactDictionary.ContactInformationDictionary.Add(
            type, this.GetContactInformation(type));
    }

    return contactDictionary;
}

The IContact.Settings property returns an IContactSettingDictionary object that contains custom properties about the contact.

C# Copy code Copy code
public IMClientContactSettingDictionary Settings
{
    get
    {
       // The IMClientContactSettingDictionary class implements
       // the IContactSettingDictionary interface.
       return new IMClientContactSettingDictionary();
    }
}

The IContact.CustomGroups property returns an IGroupCollection object that includes all of the groups of which the contact is a member.

C# Copy code Copy code
public IMClientGroupCollection CustomGroups
{
    get {
       // The IMClientGroupCollection class implements
       // the IGroupCollection interface.
        return new IMClientGroupCollection();
    }
}

ISelf interface

During the initialization process, the Office application gets the data for the current user by accessing the ILyncClient.Self property, which must return an ISelf object. The ISelf interface represents the local, signed-in IM client application user.

Table 6 shows the members that must be implemented in the class that inherits from ISelf.

Note Note

Any member of the ISelf interface not listed in the table must be present but does not need to be implemented. Members that are present but not implemented can throw a NotImplementedException or E_NOTIMPL error.

Table 6. Implementation of the ISelf interface
Member | Description
Contact property | Gets the IContact object associated with the local user.

Presence, available modalities, group membership, and contact type properties for the local user are exposed through the ISelf.Contact property (which returns an IContact object). During the initialization process, the Office application accesses the ISelf.Contact property to get a reference to the contact information for the local user.

Use the following code to define a class that inherits from the ISelf interface that implements the Contact property.

C# Copy code Copy code
[ComVisible(true)]
public class IMClientSelf : ISelf
{

    // Declare a private field to store contact data for local user.
    private IMClientContact _contactData;

    // In the constructor for the ISelf object, the calling code
    // must supply contact data.
    public IMClientSelf (IMClientContact _selfContactData)
    {
        this._contactData = _selfContactData;
    }

    // When accessed, the Contact property returns a reference
    // to the IContact object that represents the local user.
    public IMClientContact Contact
    {
        get
        {
            return this._contactData as IMClientContact;
        }
    }

    // Additional implementation details omitted.
}

IContactManager and _IContactManagerEvents interfaces

The IContactManager object manages the contacts for the local user, including the local user's own contact information. The Office application uses an IContactManager object to access IContact objects that correspond to the local user's contacts.

Table 7 shows the members that must be implemented in the class that inherits from IContactManager and _IContactManagerEvents.

Note Note

Any member of the IContactManager interface not listed in the table must be present but does not need to be implemented. Members that are present but not implemented can throw a NotImplementedException or E_NOTIMPL error.

For more information about the IContactManager and _IContactManagerEvents interfaces and their members, see UCCollaborationLib.IContactManager and UCCollaborationLib._IContactManagerEvents.

Table 7. Implementation of the IContactManager and _IContactManagerEvents interfaces
Interface | Member | Description
IContactManager | GetContactByUri method | Finds or creates a new contact instance by using the contact URI.
 | CreateSubscription method | Creates an ISubscription object that can be used for batching subscriptions or queries.
 | Lookup method | Looks up a contact or distribution group.
_IContactManagerEvents | OnGroupAdded event | Raised when a group is added to a group collection. The updated group collection can be obtained from the IContactManager.Groups property.
 | OnGroupRemoved event | Raised when a group is removed from a group collection. The updated group collection can be obtained from the IContactManager.Groups property.
 | OnSearchProviderStateChanged event | Raised when a search provider's status changes.

Office calls IContactManager.GetContactByUri to get a contact's presence information, by using the SIP address of the contact. When a contact is configured for an SIP address in the Active Directory, Office determines this address for a contact and calls GetContactByUri, passing the SIP address of the contact in for the _contactUri parameter.

When Office cannot determine the SIP address for the contact, it calls the IContactManager.Lookup method to find the SIP by using the IM service. Here Office passes in the best data that it can find for the contact (for example, just the email address for the contact). The Lookup method asynchronously returns an AsynchronousOperation object. When it invokes the callback, the Lookup method should return the success or failure of the operation in addition to the URI of the contact.

C# Copy code Copy code
public IMClientContact GetContactByUri(string _contactUri)
{

    // Declare a Contact variable to contain information about the contact.
    IMClientContact tempContact = null;

    // The _groupCollections field is an IGroupCollection object. Iterate
    // over each group in collection to see if the
    // contact is a part of the group.
    foreach (IMClientGroup group in this._groupCollections)
    {
       if (group.TryGetContact(_contactUri, out tempContact))
       {
           break;
       }
    }

    // Check to see that the URI returned a valid contact. If it
    // did not, create a new contact.
    if (tempContact == null)
    {
        tempContact = IMClientContact.BuildContact(_contactUri);
    }

    // Return the contact to the calling code.
    return tempContact;

}

The Office application needs to subscribe to presence changes for an individual contact. Thus, when a contact's presence status changes, the IM server alerts the IM client application—thereby alerting the Office application. To do this, the Office application calls the IContactManager.CreateSubscription method to create a new IContactSubscription object for this request.

C# Copy code Copy code
// Declare a private field to contain an IContactSubscription object.
private IMClientContactSubscription _contactSubscription;

// Return the IContactSubscription object associated
// with the IContactManager object.
public IMClientContactSubscription CreateSubscription()
{
    return this._contactSubscription;
}

IGroup and IGroupCollection interfaces

The IGroup object represents a collection of contacts with additional properties for identifying the contact collection by a collective group name. An IGroupCollection object represents a collection of IGroup objects defined by a local user and the IM client application. The Office application uses the IGroupCollection and IGroup objects to access the local user's contacts.

Table 9 shows the members that must be implemented in the classes that inherit from IGroup and IGroupCollection in the following table.

Note Note

Any member of the IGroup interface not listed in the table must be present but does not need to be implemented. Members that are present but not implemented can throw a NotImplementedException or E_NOTIMPL error.

For more information about the IGroup and IGroupCollection interfaces and their members, see UCCollaborationLib.IGroup and UCCollaborationLib.IGroupCollection.

Table 9. Implementation of the IGroup and IGroupCollection interfaces
Interface | Member | Description
IGroupCollection | Count property | Returns the count of IGroup objects in the collection
 | Item property | Returns the IGroup object at the specified index in the collection.
IGroup | Id property | Returns the ID of the group.

When the Office application gets the information for the local user, it accesses the group memberships of the contact (local user) by calling the IContact.CustomGroups property, which returns an IGroupCollection object. The IGroupCollection must contain an array (or List) of IGroup objects. The class that derives from IGroupCollection must expose a Count property, which returns the number of items in the collection, and an indexer method, this(int), which returns an IGroup object from the collection.

IContactSubscription interface

The IContactSubscription interface allows you to specify the contacts to receive presence information updates for and the types of presence information that trigger a notification. Office applications use an IContactSubscription object to register changes to contact's presence status.

Table 10 shows the members that must be implemented in the classes that inherit from IContactSubscription.

Note Note

Any member of the IContactSubscription interface not listed in the table must be present but does not need to be implemented. Members that are present but not implemented can throw a NotImplementedException or E_NOTIMPL error.

For more information about the IContactSubscription interface and its members, see UCCollaborationLib.IContactSubscription.

Table 10. Implementation of the IContactSubscription interface
Member | Description
AddContact method | Adds a contact to the subscription object.
Subscribe method | Helps the IM client application to monitor presence for a contact.

The IContactSubscription interface must contain a reference to all the IContact objects that it monitors, using an array or a List. The IContactSubscription.AddContact method adds an IContact object for the to the underlying data structure of the IContactSubscription object, thereby adding a new contact to monitor for presence changes.

C# Copy code Copy code
// Store references to all of the IContact objects to subscribe to.
private List<IMClientContact> _subscribedContacts;

// Add a new IContact object to the collection of contacts.
public void AddContact(IMClientContact _contact)
{
    this._subscribedContacts.Add(_contact);
}

The IContactSubscription.Subscribe method allows an IM client application to access presence observers for the contact. It can use a polling strategy to get the presence from the server for the contacts for that the IM client application has subscribed to. The Subscribe method is helpful in situations where presence is requested for someone outside of a user's contact list (for example, from a larger public network).

IContactEndPoint interface

The IContactEndPoint represents a telephone number from a contact's collection of telephone numbers.

Table 11 shows the members that must be implemented in the classes that inherit from IContactEndPoint.

Note Note

Any member of the IContactEndPoint interface not listed in the table must be present but does not need to be implemented. Members that are present but not implemented can throw a NotImplementedException or E_NOTIMPL error.

For more information about the IContactEndPoint interface and its members, see UCCollaborationLib.IContactEndpoint.

Table 11. Implementation of the IContactEndPoint interface
Member | Description
DisplayName property | Gets the display string.
Type property | Gets the contact endpoint type
Uri property | Gets the contact URI.

ILocaleString interface

The ILocaleString is a localized string structure that contains both a localized string and the locale ID of the localization. The ILocaleString interface is used to format the custom status string on the contact card.

Table 12 shows the members that must be implemented in the classes that inherit from ILocaleString.

Note Note

Any member of the ILocaleString interface not listed in the table must be present but does not need to be implemented. Members that are present but not implemented can throw a NotImplementedException or E_NOTIMPL error.

For more information about the ILocalString interface and its members, see UCCollaborationLib.ILocaleString.

Table 12. Implementation of the ILocaleString interface
Member | Description
LocaleId property | Gets the locale ID.
Value property | Gets the string.

Additional resources

  • UCCollaborationLib namespace


Office Telemetry Log

 Copy code hover
[image]

Office Telemetry Log
Send feedback

Published: November 27, 2012

Find information about the Telemetry Log that is included with Office 2013.

Applies to: Office 2013

Explore these links to learn more about using the Telemetry Log for Office 2013 and interpreting the results that it displays.

In this section

  • Troubleshooting Office files and custom solutions with the Office Telemetry Log

  • Compatibility issues in Office 2013


Troubleshooting Office files and custom solutions with the Office Telemetry Log

 Copy code hover
[image]

Troubleshooting Office files and custom solutions with the Office Telemetry Log
Send feedback

Published: March 5, 2013

Use the Telemetry Log for Office 2013 to determine compatibility issues with Office 2013 and solutions built for previous versions of Office.

Applies to: Office 2013

In this article
Introduction
How the Telemetry Log works
File and solution types tracked in the Office Telemetry Log
Using the Office Telemetry Log
Events displayed in the Office Telemetry Log
Conclusion
Additional Resources

The following article describes the Telemetry Log and how to use it. For more information about specific results displayed in the Telemetry Log, see Compatibility issues in Office 2013.

Introduction

Over the course of many releases, Microsoft has provided tools and frameworks for customizing, automating, and extending Office. This has enabled businesses and users to build solutions or add-ins for Office applications to improve their productivity and efficiency. These solutions can range in complexity from simple Visual Basic for Applications (VBA) macros to robust .NET Framework customizations. Many users who have these solutions rely on them to complete business-critical tasks and may not even know that they are using a customization that is added to their Office applications.

With such a proliferation of Office solutions, upgrading versions of Office can be complex. Enterprises and users do not know whether their important and valuable solutions are completely compatible with the new version. Their solutions might use features and computer code that are available in previous versions of Office that have been deprecated in later versions. If a solution that uses a deprecated feature is loaded into the "host" application, the solution might behave differently, cause an error, fail to load, or cause the host application to fail.

The Telemetry Log for Office 2013, a tool built upon Excel 2013, helps developers and experienced users diagnose compatibility issues by displaying events that occur within select Office 2013 applications. Using this tool, users can determine potential issues with add-ins that they use in their work environment, giving enterprise decision-makers the information that they need to decide whether to upgrade to Office 2013. The Telemetry Log also gives detailed feedback about specific changes or deprecations in the object models for the Office 2013 applications, which helps developers quickly identify and refactor problematic code or controls. IT professionals can view trends in solution health across multiple clients by using the Telemetry Dashboard for Office 2013, a companion tool to the Telemetry Log.

For more information, see Deploy Office Telemetry Dashboard.

How the Telemetry Log works

When an Office file or solution is loaded, used, closed, or raises an error in one of the selected Office 2013 applications, the application adds a record in a local data store (a database on the same computer) that includes information about the event. The record includes a title for the event, the application that logged the event, the time, the name of the file or solution, the severity, and a short description of any errors that may have occurred. When refreshed, the Telemetry Log workbook displays a list of the records contained in the local data store.

Note Note

The default location for the local data store is %Users%\[Current user]\AppData\Local\Microsoft\Office\15.0\Telemetry. The default maximum size for the data store is 5 MB (5,120 KB).

Selected Office 2013 applications have a run-time logging API that creates a record in the local data store every time that a file or solution raises one of the following events:

  • OnLoad: A record is logged in the local data store when a file or solution is loaded into specific Office 2013 applications. The run-time error logging records the file name, location, and other information in the local data store when an OnLoad event is raised.

  • OnClose: A record is logged when a file or solution is closed within the application. The record includes the name of the solution or file, its location, and the application that logged the event.

  • OnError: A record is logged when an error is found in a solution for certain Office 2013 applications. The record includes the name of the solution or file and the run-time failure or compatibility issue that the user encountered. When possible, errors are mapped to known compatibility issues and are displayed as such in the Telemetry Log.

The Telemetry Log displays information about a large list of files and solution types for a selection of Office 2013 applications. The type of files and solutions that are monitored by the run-time logging APIs vary by application. See the Table 1 for more information about what kinds of solutions are monitored.

Table 1. Types of Office files and solutions tracked in Telemetry Log

Solution type

Applications

Description

Task pane apps

Excel 2013, Word 2013, Project 2013

These are apps for Office that are hosted in a task pane within the client application.

Content apps

Excel 2013

These are apps for Office that are integrated into the content of the Office file.

Mail apps

Outlook 2013

These are apps that appear inOutlook 2013 when certain conditions are met (the e-mail body or subject includes particular words or phrases).

Active documents

Word 2013

PowerPoint 2013

Excel 2013

Active documents are any Office document files other than the other solution types listed in this table. This can include the following:

  • Office binary format files (.doc, .ppt, .pps, .xls).

  • Office OpenXML format files (.docx, .pptx, .ppsx, .xlsx).

  • Macro-enabled files that contain VBA code (.docm, .dotm, .pptm, .potm, .xlsm, .xltm).

  • Files that contain ActiveX controls.

  • Files that have External Data Connections.

COM add-ins

Word 2013

PowerPoint 2013

Excel 2013

Outlook 2013

COM add-ins include Office development tools in Visual Studio 2010 application-level add-ins.

Excel Automation add-ins

Excel 2013

This solution type includes previous versions of Excel-supported Automation Add-ins, which are built upon COM add-ins. Functions in Automation add-ins can be called from formulas in Excel worksheets.

Excel XLL add-ins

Excel 2013

XLL add-ins (.xll) are specific to Excel and built with any compiler that supports building DLLs (dynamic-link libraries). They do not have to be installed or registered. XLL add-ins also include DLLs that contain user-defined commands and functions.

Excel XLS RTD add-ins

Excel 2013

XLS real-time data (RTD) add-ins are Excel worksheets that use the RealTimeData worksheet function to call an Automation server to retrieve data in real-time.

Word WLL add-ins

Word 2013

WLL (.wll) add-ins are specific to Word and built with any compiler that supports building DLLs.

Application add-ins

Word 2013

PowerPoint 2013

Excel 2013

Application add-ins are application-specific files that contain VBA code. These include macro-enabled Word templates (.dotm), Excel add-ins (.xla, .xlam), and PowerPoint add-ins (.ppa, .ppam).

Templates

Word 2013

PowerPoint 2013

Excel 2013

Templates include document (.dot, .dotx), worksheet (.xlt, .xltx), or presentation (.pot, .potx) templates that are attached to an Office file.

Using the Office Telemetry Log

When you install Office 2013, the Telemetry Log is installed, the local data store is created on the same computer, and the run-time logging APIs are enabled in the Office 2013 applications previously listed. However, a solution or file must be loaded or opened in the application before the Telemetry Log can start to monitor it.

Use the following procedure to display the recorded Office issues in the Telemetry Log.

To use the Telemetry Log

  1. To open the Telemetry Log, do one of the following:

    • On Windows 7: On the Start menu, choose All Programs. Then, in the list of programs, expand Microsoft Office 2013, expand Office 2013 Tools, and then click Office 2013 Telemetry Log.

      A new workbook in Excel 2013 opens. The workbook has three worksheets titled EventsSystem info, and Guide.

    • On Windows 8: Swipe up to display the AppBar, choose All Apps, and then choose Office 2013 Telemetry Log.

      A new workbook in Excel 2013 opens. The workbook has three worksheets titled EventsSystem info, and Guide.

  2. To view an up-to-date list of events, on the Events worksheet, at the top of the worksheet, choose Refresh.

  3. To view the event data that is collected from Office 2013 applications, review the table displayed on the Events worksheet.

  4. To review information about the computer on which Office 2013 and Telemetry Log are installed, review the information displayed on the System Info worksheet.

Note Note

It is not necessary to save the Telemetry Log workbook in Excel 2013 to keep a record of the results, because the information is stored in the local data store (which is separate from the Telemetry Log). However, saving the workbook does not damage the Telemetry Log.

The Telemetry Log displays some simple information about the recorded events. Each record displayed in the Telemetry Log contains a title and lists the severity of the event displayed. For errors, the records also include a description of the error together with steps to address the issue. Keep in mind that not all of the records displayed represent errors caused by Office solutions; the Telemetry Log also shows when solutions and files are loaded or closed successfully.

For example, the issue titled "OM Hidden: Comment.Initial Property" appears if a solution or macro-enabled file opened in Word 2013 attempts to get the initials of a commenter who is associated with a comment. Word 2013 features an improved commenting experience that does not display commenter initials by default. The APIs associated with the older commenting model have been hidden in the Word 2013 object model but remain available for backwards-compatibility. The "OM Hidden: Comment.Initial" issue in the indicates the file that attempted to use the API, the application that raised the event (Word 2013), the time and date of the event, and short description about the error and how to fix it.

Figure 1. Office Telemetry Log

The Office Event Viewer displaying records.

Note Note

The System Info worksheet in the Telemetry Log contains information about the computer on which Office 2013 is installed. The worksheet displays the following information:

  • User name.

  • Full computer name.

  • Architecture of the operating system (x64/64-bit or x86/32-bit).

  • Version of Windows that is installed on the computer.

  • Time zone for the computer's internal clock.

  • Version of the Telemetry Log.

  • Version of Office that is installed on the computer.

This information can be useful when you are interpreting the issues and events listed on the Events worksheet.

In the Telemetry Log, a level of severity is displayed together with the known issues. From the previous example, an issue in which a part of the object model has been hidden most often has an "Informative" level of severity. On the other hand, other known issues might be more serious and require more immediate action. The severity of the issues displayed in the Telemetry Log can be one of the following:

  • Information The issue may not have an immediate effect on application compatibility, but the user may have to take an action later. Many issues of the "OM hidden" type have this severity level.

  • Warning The issue could cause data loss or result in reduced visual fidelity.

  • Critical The issue could cause significant loss of functionality or lead the application to crash.

Table 2. Types of events displayed in the Telemetry Log

Use the following table (Table 2) to interpret the records that are displayed in the Telemetry Log.

Event ID

Title

Severity

Description

1

Document loaded successfully

The file listed in the File column was opened in the Office application without any issues.

2

Document failed to load

Warning

The application was unable to load the file. There may be some underlying compatibility issue.

  • For more information about how to repair a corrupted workbook in Excel 2013, see Repairing a corrupted workbook.

  • For more information about how to repair a corrupted document in Word 2013, see Save and recover a backup copy of a document

3

Template loaded successfully

The template file listed in the File column was opened in the Office application without any issues.

4

Template failed to load

Warning

The application was unable to load the template file. There may be some underlying compatibility issue or the template availability may have changed.

  • For more information about how to repair a corrupted workbook in Excel 2013, see Repairing a corrupted workbook.

  • For more information about how to repair a corrupted document in Word 2013, see Save and recover a backup copy of a document

5

Add-in loaded successfully

The add-in listed in the File column loaded within the Office application successfully. No compatibility issues were detected.

6

Add-in failed to load

Critical

The application was unable to load the add-in listed in the File column.

  • For more information about how to repair a corrupted workbook in Excel 2013, see Repairing a corrupted workbook.

  • For more information about how to repair a corrupted document in Word 2013, see Save and recover a backup copy of a document

7

App manifest downloaded successfully

The host application loaded the manifest for the app for Office successfully.

8

App manifest did not download

Critical

The host application was unable to load the manifest file for the app for Office from the SharePoint catalog, corporate catalog, or the Office Store.

9

App manifest could not be parsed

Critical

The host application loaded the app for Office manifest for the app, but could not read the XML.

10

App used too much CPU

Critical

The app for Office used more than 90% of the CPU resources over a finite period of time.

11

Application crashed on load

Critical

The Office application tried to load a document or solution when it launched, but problems with the document or solution prevented the application from launching.

12

Application closed due to a problem

Critical

Something caused a critical error in the application and it needed to close.

13

Document closed successfully

The file listed in the File column closed successfully.

14

Application session extended

Application sessions with a particular document or solution open should only last 24 hours. If a session goes over 24 hours, the host application creates a new session.

15

App disabled due to string search time-out

Mail apps search the subject line and message of an e-mail to determine whether they should be displayed by using a regular expression. The mail app listed in the File column was disabled by Outlook 2013 because it timed out repeatedly while trying to match a regular expression.

16

Document open when application crashed

Critical

The file listed in the File column was open when the application (listed in the application column) crashed. The file may or may not have been responsible for the Application crash.

17

Add-in closed successfully

Informative

The application was able to shut down the add-in successfully.

18

App closed successfully

The host application was able to close the app for Office successfully.

19

App encountered runtime error

Critical

The app for Office had a problem that caused it to fail. For more details, look at the Microsoft Office Alerts log using the Windows Event Viewer on the computer that encountered the error.

20

App failed to verify licensing

Critical

The licensing information for the app for Office could not be verified and may have expired. For more details, look at the Microsoft Office Alerts log using the Windows Event Viewer on the computer that encountered the error.

Various

"OM Behavior Change: ..."

Informative

The add-in or macro-enabled document code uses an object, member, collection, enumeration, or constant that behaves differently from previous versions of Office.

For more information, see Compatibility issues in Office 2013.

Various

"OM Removed: …"

Critical

The add-in or macro-enabled document code uses an object, member, collection, enumeration, or constant that has been removed from the object model.

For more information, see Compatibility issues in Office 2013.

Various

"OM Hidden: …"

Informative

The add-in or macro-enabled document code uses an object, member, collection, enumeration, or constant that has been hidden in the object model.

For more information, see Compatibility issues in Office 2013.

Various

"Control: …"

The file contains a control that may not be supported in Office 2013 or on the computer's operating system.

For more information, see Compatibility issues in Office 2013.

Conclusion

The Telemetry Log provides large enterprises, individual users, and developers with a simple tool for monitoring their critical Office solutions. By identifying problematic Office solutions before a large-scale upgrade, businesses can more reasonably predict the cost of adopting Office 2013.

Additional Resources

  • Office Developer Center

  • Compatibility issues in Office 2013

  • Deploy Office Telemetry Dashboard

  • Office Developer Center


Compatibility issues in Office 2013

 Copy code hover
[image]

Compatibility issues in Office 2013
Send feedback

Published: November 27, 2012

Get more information about issues displayed in the Telemetry Log about possible compatibility issues in Office 2013 products, including Excel 2013, Word 2013, and Outlook 2013.

Applies to: Office 2013

In this article
Controls
Removed members in the Object Model
Behavior changes in the Object Model
Hidden members in the Object Model

The following tables list information about issues presented in the Telemetry Log. For more information about the Telemetry Log, see the article Troubleshooting Office files and custom solutions with the Office Telemetry Log.

Controls

These messages can appear if the file contains a control that may not be supported in Office 2013 or on the computer operating system.

Table 1. Issues displayed in Telemetry Log about controls
Event ID | Applications | Additional information | Title | Description
10000 | All Office 2013 |  | Warning: Visual Basic 6.0 Controls | The file uses a Visual Basic 6.0 control that does not work in 64-bit versions of Office or in 32-bit versions of Office that are running on a device that uses an ARM processor. Replace the control with a supported control if you want it to be available to Office applications in those environments.
10001 | All Office 2013 | Link | Controls: Visual Basic 6.0 Control on 64-bit OS | The file uses a Visual Basic 6.0 control that does not work in 64-bit versions of Office. Visual Basic 6.0 runtime files are 32-bit and are supported in the 32-bit OS or in WOW emulation environments only.
10002 | All Office 2013 | Link | Controls: Visual Basic 6.0 Controls on Device with ARM Processor | The file uses a Visual Basic 6.0 control that does not work on a device that uses an ARM processor.
10003 | All Office 2013 | Link | Controls: Microsoft Calendar Control | The file uses the Microsoft Calendar control (Mscal.ocx), a feature of previous versions of Access that is not available in Office 2013. The control will not work because it is not installed on the host computer. Use other date picker controls as an alternative, like the Date Picker Content Control (in Word 2013) or the Windows DatePicker control (in the Windows Common Controls). For more information, see Replacing the Calendar Control in Access 2010 Applications.
10004 | All Office 2013 | Link | Office Web Components | The file uses an Office Web Components (MSOWC.dll) control. The control will not work because the Office Web Components are not installed on this computer and are not included with Office 2013. To use this control, install the Office Web Components separately. For more information, see HOW TO: Find Office Web Components Programming Documentation and Samples
10005 | All Office 2013 | Link | Controls: Unregistered ActiveX Control | The file uses ActiveX controls that are not registered on the host computer. To use the control, register it on the host computer.

Removed members in the Object Model

These messages can appear if the add-in or macro-enabled document code uses an object, member, collection, enumeration, or constant that has been removed from the application's object model.

Table 2. Issues displayed in Telemetry Log about removed members

Event ID

Applications

Additional Information

Title

Description

10103

Word 2013, Outlook 2013

Link

OM Removed: Custom XML Feature

The Custom XML feature is removed from Word. The following methods and properties are hidden, and if accessed, return run-time error:

  • XMLNodes.Add method

  • Document.XMLHideNamespaces property

  • Document.XMLSaveDataOnly property

  • Document.XMLSchemaViolations property

  • XMLSchemaViolations object and all its members

  • XMLSchemaViolation object and all its members

  • Application.TaskPanes, if the wdTaskPaneXMLStructure constant (5) of the WdTaskPanes enumeration is specified

  • Options.PrintXMLTag property

  • View.ShowXMLMarkup property

  • XMLChildNodeSuggestions collection and all its members

  • XMLChildNodeSuggestion object and all its members

  • Selection.XMLParentNode property

  • Range.XMLParentNode property

10113

Word 2013, Outlook 2013

OM Removed: Smart Tag Feature

The SmartTags feature is removed from Word. The following objects, methods, and properties are hidden, and if accessed, return a runtime error:

  • SmartTag object and members

  • SmartTags collection and members

  • SmartTagAction object and members

  • SmartTagActions collection and members

  • SmartTagType object and members

  • SmartTagTypes collection and members

  • XMLNode.SmartTag property

The following methods are hidden, and if accessed, fail silently:

  • Document.CheckNewSmartTags method

  • Document.RecheckSmartTags method

  • Document.RemoveSmartTags method

The following properties are hidden, and if accessed, always returns FALSE:

  • Document.EmbedSmartTags property

  • Document.SmartTagsAsXMLProps property

  • Options.LabelSmartTags property

  • Options.DisplaySmartTagButtons property

  • EmailOptions.EmbedSmartTag property

The following property is hidden, and if accessed, always returns true:

  • View.DisplaySmartTags property

The following properties are hidden, and if accessed, always returns an empty collection:

  • Application.SmartTagTypes property

  • Document.SmartTags property

  • Range.SmartTags property

  • Selection.SmartTags property

10115

Word 2013, Outlook 2013

OM Removed: AutoSummary Feature

The AutoSummary feature is removed from Word. The following method and properties are hidden, and if accessed, return a runtime error:

  • Document.AutoSummarize method

  • Document.ShowSummary property

  • Document.SummaryViewMode property

  • Document.SummaryLength property

10116

Word 2013, Outlook 2013

OM Removed: Barcode Feature

The barcode feature for envelopes is removed from Word. The following properties are hidden, and if accessed, always return FALSE:

  • Envelope.DefaultPrintBarCode property

  • MailingLabel.DefaultPrintBarCode property

10117

Word 2013, Outlook 2013

OM Removed: Window.DocumentMapPercentWidth Property

The Window.DocumentMapPercentWidth property is hidden in Word. If accessed, the property raises a run-time error.

10122

Word 2013, Outlook 2013

OM Removed: Application.FileSearch

The Application.FileSearch was removed in Office 2007. If accessed, this property will return an error. To work around this issue, use the FileSystemObject to recursively search directories to find specific files.

10145

Excel 2013

OM Removed: Application.FileSearch

The Application.FileSearch property was removed in Office 2007. If accessed, this property will return an error. To work around this issue, use the FileSystemObject to recursively search directories to find specific files.

10154

Excel 2013

OM Removed: Smart Tag Feature

The SmartTags feature is removed from Excel. The following properties are hidden, and if accessed, always returns FALSE:

  • Application.SmartTagRecognizers property

The following objects, methods, and properties are hidden, and if accessed, return a runtime error:

  • SmartTag object and members

  • SmartTags collection and members

  • SmartTagAction object and members

  • SmartTagActions collection and members

  • SmartTagOptions collection and members

  • SmartTagRecognizer object and members

  • SmartTagRecognizers collection and members

The following methods are hidden, and if accessed, fail silently:

  • Workbook.RecheckSmartTags method

The following properties are hidden, and if accessed, always returns an empty collection:

  • Workbook.SmartTagOptions property

  • Worksheet.SmartTags property

  • Range.SmartTags property

  • IRange.SmartTags property

  • DialogSheet.SmartTags property

  • IDialogSheet.SmartTags property

10155

All Office 2013

OM Removed: ToolbarButton.Edit Method

The CommandBar Button Editor has been removed. If called, the method silently fails. Custom images can be applied to legacy CommandBar buttons using the CommandBarButton.PasteFace method, or the CommandBarButton.Picture and the CommandBarButton.Mask properties.

Behavior changes in the Object Model

These messages can appear if the add-in or macro-enabled document code uses an object, member, collection, enumeration, or constant that behaves differently from previous versions of Office.

Table 3. Issues displayed in Telemetry Log about behavior changes

Event ID

Applications

Additional Information

Title

Description

10100

Word 2013, Outlook 2013

OM Behavior Change: Options.RevisedLinesColor Property

Change Bars have been become interactive components of the user interface and are not distinguished by color in Word. If accessed, the Options.RevisedLinesColor property always returns the value for wdBlack (1).

10101

Word 2013, Outlook 2013

Link

OM Behavior Change: Custom XML Feature

The Custom XML feature is hidden in Word. Word does not support the embedding of custom XML in documents. Some APIs associated with accessing the Custom XML remain but are changed:

  • Range.InsertXML and Selection.InsertXML methods succeed, but any custom XML markup in the input is not loaded.

  • Source.XML, Selection.XML, Range.XML, CustomXMLNode.XML Property (Office), CustomXMLPart.XML Property (Office), Range.WordOpenXML, Selection.WordOpenXML, XMLNode.WordOpenXML, and Document.WordOpenXML properties succeed, but any custom XML markup in the file is not returned.

  • XMLNodes collection is hidden and always returns an empty set.

  • Application.ArbitraryXMLSupportAvailable property always returns FALSE.

10104

Outlook 2013

Link

OM Behavior Change: CommandBars Feature

CommandBars in Outlook have been replaced by the ribbon component of the Fluent user interface. If accessed, the Explorer.CommandBars and Inspector.CommandBars properties will return null. To customize the user interface in Outlook, use the IRibbonExtensibility Object (Office) object and the RibbonX extensibility model.

10105

Excel 2013

OM Behavior Change: Application.Hwnd Property

The Application.Hwnd property is changed. If accessed, the property returns the handle of the active window in Excel rather than handle of the top-level window. To access another window in Excel, use the Application.Windows property.

10106

Excel 2013

OM Behavior Change: Application.FormulaBarHeight Property

The Application.FormulaBarHeight property is changed. If accessed, the property reads and writes the height of the formula bar associated with the active window in Excel. To change formula bar height for another window in Excel, set the Application.FormulaBarHeight property after activating the window.

10107

Excel 2013

OM Behavior Change: Workbook.Protect Method

Window structure (height, width, minimized or maximized state) cannot be protected in Excel. If called, the Workbook.Protect method does not protect the workbook window structure regardless of the value of the Windows parameter.

10140

Word 2013, Outlook 2013

OM Behavior Change: Table.AllowPageBreaks

The Table.AllowPageBreaks property is hidden, and always returns TRUE. To achieve the same behavior, use the ParagraphFormat.KeepTogether and ParagraphFormat.KeepWithNext properties.

Hidden members in the Object Model

These messages can appear if the add-in or macro-enabled document code uses an object, member, collection, enumeration, or constant that has been hidden in the application's object model.

Table 4. Issues displayed in Telemetry Log about hidden members

Event ID

Applications

Additional Information

Title

Description

10108

Word 2013, Outlook 2013

OM Hidden: Document.EditionOptions Method

The Document.EditionOptions method is hidden in Word. This method was intended to support the infrastructure for Microsoft Visual Studio Tools for Office and was not intended to be used directly within user code.

10109

Word 2013, Outlook 2013

OM Hidden: Document.UpdateSummaryProperties Method

The AutoSummary feature is removed from Word. If called, the Document.UpdateSummaryProperties method raises a run-time error.

10110

Word 2013, Outlook 2013

OM Hidden: Comment.Delete Method

Commenters can reply directly to other comments in Word. If called, the Comment.Delete method functions similar to previous versions of Office by deleting a single comment and leaving all replies in the document. To remove an entire thread of comments, use the Comment.DeleteRecursively method. To reply to a comment, use the Comment.Replies.Add method.

10111

Word 2013, Outlook 2013

OM Hidden: Comment.Author Property

Comments in Word are now associated with contacts. If accessed, the Comment.Author property behaves similarly to previous versions of Office. To access the name of a commenter, use the Name property of the Contact object associated with the comment.

10112

Word 2013, Outlook 2013

OM Hidden: Comment.Initial Property

Initials of commenters are not displayed with comments in Word by default. If accessed, the Comment.Initial property behaves similar to previous versions of Office. However, printed documents still display initials for comments.

10114

Word 2013, Outlook 2013

OM Hidden: Comment.ShowTip Property

ScreenTips associated with comments in Word are shown by default. If accessed, the Comment.ShowTip property always returns FALSE.

10118

Word 2013, Outlook 2013

OM Hidden: Options.BackgroundOpen Property

Large web documents cannot be opened in the background in Word. If accessed, the Options.BackgroundOpen property always returns FALSE and cannot be set to any other value.

10119

Word 2013, Outlook 2013

OM Hidden: Document.ApplyQuickStyleSet Method

The Document.ApplyQuickStyleSet method is hidden in Word. If called, the method continues to function the same as it did in Office 2007 by changing the Style Set for the document. To use the new features of Office 2010 and above, replace with the Document.ApplyQuickStyleSet2 method.

10120

Word 2013, Outlook 2013

OM Hidden: Document.SaveAs Method

The Save As feature behaves similarly to previous versions of Word. If called, the Document.SaveAs method behaves similarly as it does in Office 2007. And SaveAs2 method is added to the Document object that contains the properties introduced in Office 2010. To use the new features of Office 2010 and above, replace the Document.SaveAs method with the Document.SaveAs2.

10121

Word 2013, Outlook 2013

OM Hidden: Assistant and AnswerWizard Features

The Assistant and AnswerWizard features have been hidden in Word.

The following properties are hidden but remain part of the object model for backward compatibility. It is not recommended to use them in new Office solutions:

  • Application.Assistant property

  • Application.AnswerWizard property

The following properties are hidden. If accessed, they return a run-time error.

  • Global.Assistant property

  • Global.AnswerWizard property

10123

Word 2013, Outlook 2013

OM Hidden: Options.WPHelp

The Options.WPHelp property is hidden.

10124

Word 2013, Outlook 2013

OM Hidden: Options.SetWPHelpOptions

The Options.SetWPHelpOptions property is hidden. If accessed, the property returns an error.

10125

Word 2013, Outlook 2013

OM Hidden: Options.WPDocNavKeys

The Options.WPDocNavKeys property is hidden. If accessed, the property always returns FALSE.

10126

Word 2013, Outlook 2013

OM Hidden:Options.BlueScreen

The Options.BlueScreen property is hidden. If accessed, the property always returns FALSE.

10127

Word 2013, Outlook 2013

OM Hidden: Options.AllowFastSave

The Options.AllowFastSave is hidden. If accessed, the property always returns FALSE.

10128

Word 2013, Outlook 2013

OM Hidden: Application.DisplayStatusBar

The Application.DisplayStatusBar property is hidden. Use Application.CommandBars("Status Bar")Visible instead.

10129

Word 2013Outlook 2013

OM Hidden: Document.HTMLProject

The Document.HTMLProject is hidden. If accessed, the property returns an error.

10130

Word 2013, Outlook 2013

OM Hidden: Document.Versions

The Versions feature is removed, and as a result, the Document.Versions property is hidden. If accessed, the property returns an error.

10131

Word 2013, Outlook 2013

OM Hidden: Document.Route

The Routing Slip feature is removed, and as a result, the Document.Route method is hidden. If accessed, this method returns an error.

10132

Word 2013, Outlook 2013

OM Hidden: Document.HasRoutingSlip

The Routing Slip feature is removed, and as a result, the Document.HasRoutingSlip property is hidden. If accessed, the property returns an error.

10133

Word 2013, Outlook 2013

OM Hidden: Document.Routed

The Routing Slip feature is removed, and as a result, the Document.Routed property is hidden. If accessed, the property returns an error.

10134

Word 2013, Outlook 2013

OM Hidden: Document.RoutingSlip

The Routing Slip feature is removed, and as a result, the Document.RoutingSlip property is hidden. If accessed, the property returns an error.

10135

Word 2013, Outlook 2013

OM Hidden: Diagram OM

The Diagram object and the properties and methods associated with the Diagram object have been hidden. If accessed, the following members generate errors:

  • Shapes.AddDiagram

  • Shape.Diagram

  • Shape.DiagramNode

  • Shape.HasDiagram

  • ShapeHasDiagramNode

  • ShapeRange.DiagramNode

  • ShapeRange.HasDiagram

  • ShapeRange.HasDiagramNode

10136

Word 2013, Outlook 2013

OM Hidden: ShapeRange.Activate

The Word Picture object is hidden, and as a result, the methods used to convert a picture to a Word Picture object were also hidden. These methods included the following:

  • InlineShape.Activate

  • Shape.Activate

  • ShapeRange.Activate

If used, these methods generate an error.

10137

Word 2013, Outlook 2013

OM Hidden: Shape.Activate

The Word Picture object is hidden, and as a result, the methods used to convert a picture to a Word Picture object were also hidden. These methods included the following:

  • InlineShape.Activate

  • Shape.Activate

  • ShapeRange.Activate

If used, these methods generate an error.

10138

Word 2013, Outlook 2013

OM Hidden: InlineShape.Activate

The Word Picture object is hidden, and as a result, the methods used to convert a picture to a Word Picture object were also hidden. These methods included the following:

  • InlineShape.Activate

  • Shape.Activate

  • ShapeRange.Activate

If used, these methods generate an error.

10139

Word 2013

OM Hidden: Shapes.AddChart

The Shapes.AddChart method is hidden. It remains part of the object model for backward compatibility, but you should not use it in new applications. Use the Shapes.AddChart2 method instead.

Note Note

The Shapes.AddChart2 method applies a default title to the new chart. If you need to change the title of the chart after it has been added to the file, use the Chart.ChartTitle property or edit the title manually.

10141

Word 2013, Outlook 2013

OM Hidden: Application.ShowWindowsInTaskbar

The Application.ShowWindowinTaskbar property is hidden. If accessed, the property always returns true.

10142

Word 2013, Outlook 2013

OM Hidden: HangulHanjaConversionDictionaries.BuiltinDictionary

The HangulHanjaConversionDictionaries.BuiltinDictionary property is hidden. If accessed, the property returns NULL.

10143

Word 2013, Outlook 2013

OM Hidden: Template.AutoTextEntries

AutoText is now a type of Building Block. You can access Building Blocks by using the Template.BuildingBlockEntries or Template.BuildingBlockTypes properties.

By default, AutoText is saved in normal.dotm

10144

Word 2013, Outlook 2013

OM Hidden: View.RevisionsMode

The View.RevisionsMode property is hidden. Instead, use the View.MarkupMode property.

10146

Excel 2013

OM Hidden: ISlicerCache.ClearManualFilter

The method ClearManualFilter of ISlicerCache object was marked as hidden. It remains part of the object model for backward compatibility, but you should not use it in new applications.

10147

Excel 2013

OM Hidden: _Application.ShowWindowsInTaskbar

The property _Application.ShowWindowsInTaskbar has been hidden. It remains part of the object model for backward compatibility, but you should not use it in new applications.

10148

Excel 2013

OM Hidden: _Application.SaveISO8601Dates

The property _Application.SaveISO8601Dates has been hidden. It remains part of the object model for backward compatibility, but you should not use it in new applications.

10149

Excel 2013

OM Hidden: SlicerCache.ClearManualFilter

The method ClearManualFilter of SlicerCache. object was marked as hidden. It remains part of the object model for backward compatibility, but you should not use it in new applications.

10150

Excel 2013

OM Hidden: _Application.Assistant

The property _Application.Assistant has been hidden. It remains part of the object model for backward compatibility, but you should not use it in new applications.

10151

Excel 2013

OM Hidden: _Application.AnswerWizard

The property _Application.Assistant has been hidden. If accessed, the property returns a run-time error.

10152

Excel 2013

OM Hidden: _Global.Assistant

The property _Global.Assistant has been hidden. It remains part of the object model for backward compatibility, but you should not use it in new applications.

10153

Excel 2013

OM Hidden: Shapes.AddChart

The Shapes.AddChart method is hidden. It remains part of the object model for backward compatibility, but you should not use it in new applications. Use the Shapes.AddChart2 method instead.

Note Note

The Shapes.AddChart2 method applies a default title to the new chart. If you need to change the title of the chart after it has been added to the file, use the Chart.ChartTitle property or edit the title manually.

Additional resources

  • Office Developer Center

  • Troubleshooting Office files and custom solutions with the Office Telemetry Log

  • Office Application Compatibility Forum

  • Microsoft Consulting Services

  • Deploy Office Telemetry Dashboard


Welcome to the object library reference for Office 2013

 Copy code hover
[image]

Welcome to the object library reference for Office 2013
Send feedback

This reference contains conceptual overviews, programming tasks, samples, and references to guide you in developing solutions based on Office 2013.

We welcome your comments or questions about this content. You can send feedback to docthis@microsoft.com.

Initial publication: July 2012 | Updated: March 2013

This documentation contains the following sections:

  • Concepts: Provides important concepts for developing custom Office solutions.

  • How do I: Provides a list of how-to topics for developing custom Office solutions.

  • Reference: Provides reference materials for the Office object model.

Additional resources

  • Microsoft Office Developer Center

  • Accessibility in Microsoft Products

  • Document Conventions

  • Object Library Reference for Microsoft Office 2010 Copyright Notice

  • Microsoft Online Privacy Notice


Concepts (object library reference for Office 2013)

 Copy code hover
[image]

Concepts (object library reference for Office 2013)
Send feedback

This section contains the following overviews about programmability in Microsoft Office 2013:

  • Getting Help on Macintosh Keywords

  • OLE Programmatic Identifiers

  • Overview of the Office Fluent Ribbon

  • Office Fluent Ribbon Customization in Microsoft Access

  • Using the Document Inspector

  • Security Notes for Microsoft Office Solutions Development


Getting Help on Macintosh Keywords (Office)

 Copy code hover
[image]

Getting Help on Macintosh Keywords (Office)
Send feedback

You have requested Help for a Visual Basic keyword that is used only on the Macintosh; for more information, see the language reference Help that is included with Microsoft Office Macintosh Edition.


OLE Programmatic Identifiers (Office)

 Copy code hover
[image]

OLE Programmatic Identifiers (Office)
Send feedback

You can use an OLE programmatic identifier (sometimes called a ProgID) to create an Automation object. The following tables list OLE programmatic identifiers for ActiveX controls and the Microsoft Office 2013 applications.

ActiveX Controls

Microsoft Access

Microsoft Excel

Microsoft Graph

Microsoft Outlook

Microsoft PowerPoint

Microsoft Word

ActiveX Controls

To create the ActiveX controls that are listed in the following table, use the corresponding OLE programmatic identifier.

To create this control | Use this identifier
CheckBox | Forms.CheckBox.1
ComboBox | Forms.ComboBox.1
CommandButton | Forms.CommandButton.1
Frame | Forms.Frame.1
Image | Forms.Image.1
Label | Forms.Label.1
ListBox | Forms.ListBox.1
MultiPage | Forms.MultiPage.1
OptionButton | Forms.OptionButton.1
ScrollBar | Forms.ScrollBar.1
SpinButton | Forms.SpinButton.1
TabStrip | Forms.TabStrip.1
TextBox | Forms.TextBox.1
ToggleButton | Forms.ToggleButton.1

Microsoft Access

To create the Microsoft Access objects that are listed in the following table, use one of the corresponding OLE programmatic identifiers. If you use an identifier without a version number suffix, you create an object in the most recent version of Access that is available on the computer where the macro is running.

To create this object | Use one of these identifiers
Application | Access.Application
CurrentData | Access.CodeData, Access.CurrentData
CurrentProject | Access.CodeProject, Access.CurrentProject

Microsoft Excel

To create the Microsoft Excel objects that are listed in the following table, use one of the corresponding OLE programmatic identifiers. If you use an identifier without a version number suffix, you create an object in the most recent version of Excel that is available on the computer where the macro is running.

To create this object | Use this identifier | Comments
Application | Excel.Application |
Workbook | Excel.AddIn |
Workbook | Excel.Chart | Returns a workbook that contains two worksheets; one for the chart and one for its data. The chart worksheet is the active worksheet.
Workbook | Excel.Sheet | Returns a workbook with one worksheet.

Microsoft Graph

To create the Microsoft Graph objects that are listed in the following table, use one of the corresponding OLE programmatic identifiers. If you use an identifier without a version number suffix, you create an object in the most recent version of Graph that is available on the computer where the macro is running.

To create this object | Use this identifier
Application | MSGraph.Application
Chart | MSGraph.Chart

Microsoft Outlook

To create the Microsoft Outlook object that are listed in the following table, use one of the corresponding OLE programmatic identifiers. If you use an identifier without a version number suffix, you create an object in the most recent version of Outlook that is available on the computer where the macro is running.

To create this object | Use this identifier
Application | Outlook.Application

To create the ActiveX controls that are specific to the Outlook forms listed in the following table, use the corresponding OLE programmatic identifier.

To create this Microsoft Office Outlook control | Use this identifier
OlkBusinessCardControl | Outlook.OlkBusinessCardControl
OlkCategory | Outlook.OlkCategoryStrip
OlkCheckBox | Outlook.OlkCheckBox
OlkComboBox | Outlook.OlkComboBox
OlkCommandButton | Outlook.OlkCommandButton
OlkContactPhoto | Outlook.OlkContactPhoto
OlkDateControl | Outlook.OlkDateControl
OlkFrameHeader | Outlook.OlkFrameHeader
OlkInfoBar | Outlook.OlkInfoBar
OlkLabel | Outlook.OlkLabel
OlkListBox | Outlook.OlkListBox
OlkOptionButton | Outlook.OlkOptionButton
OlkPageControl | Outlook.OlkPageControl
OlkSenderPhoto | Outlook.OlkSenderPhoto
OlkTextBox | Outlook.OlkTextBox
OlkTimeControl | Outlook.OlkTimeControl
OlkTimeZoneControl | Outlook.OlkTimeZone

Microsoft PowerPoint

To create the Microsoft PowerPoint object that are listed in the following table, use one of the corresponding OLE programmatic identifiers. If you use an identifier without a version number suffix, you create an object in the most recent version of PowerPoint that is available on the computer where the macro is running.

To create this object | Use this identifier
Application | PowerPoint.Application

Microsoft Word

To create the Microsoft Word objects that are listed in the following table, use one of the corresponding OLE programmatic identifiers. If you use an identifier without a version number suffix, you create an object in the most recent version of Word that is available on the computer where the macro is running.

To create this object | Use one of these identifiers
Application | Word.Application
Document | Word.Document, Word.Template
Global | Word.Global


Overview of the Office Fluent Ribbon

 Copy code hover
[image]

Overview of the Office Fluent Ribbon
Send feedback

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

The Office Fluent ribbon replaces the previous system of layered menus, toolbars, and task panes from previous versions of Office. The ribbon has a simpler system of interfaces that is optimized for efficiency and discoverability. The ribbon has improved context menus, screentips, a mini toolbar, and keyboard shortcuts that improve user efficiency and productivity. In addition, you can use Ribbon Extensibility (or RibbonX) to enhance the user experience. You use extensible markup language (XML) and one of several conventional programming languages to manipulate the components that make up the ribbon. Because XML is plain text, you can create customization files in any text editor, or you can use your favorite XML editor. You can also reuse customization files with a minimum of adjustments because each application uses the same programming model. For example, you can reuse the customization files that you create in Microsoft Word 2013, Microsoft Excel 2013, Microsoft Access 2013, or Microsoft PowerPoint 2013.

Using XML markup files to customize the ribbon greatly reduces the need to create complex add-ins that are based on the CommandBars object model. However, add-ins written in previous versions of Office continue to work in the ribbon with little or no modification. You can create application-level customizations for the ribbon in Word 2013, in Excel 2013, or PowerPoint 2013 by doing any of the following:

  • Use COM add-ins in managed or unmanaged code

  • Use application-specific add-ins, such as .ppam and .xlam files

  • Use templates (.dotm files) in Word 2010

In a typical scenario, code in the COM add-in contains procedures that return XML markup from an external customization file or from XML that is in the code itself. When the application starts, the add-in loads and executes the code that returns the XML markup. Microsoft Office validates the XML markup against an XSD schema, and then loads it into memory and applies it to the ribbon before the ribbon is displayed. Menu items and controls use callback procedures to execute code in the add-in. Document-level customizations use the same XML markup and an Open XML Formats file with one of these extensions: docx, .docm, .xlsx, .xlsm, .pptx, .or pptm. In this scenario, you create a customization file that contains the XML markup and save it to a folder. You then modify the parts in the Open XML Formats container to point to the customization file. When you open the document in the Office application, the customization file loads into memory and is applied to the ribbon. The commands and controls then call code that is contained in the document to provide their functionality.

What About Existing Solutions?

In versions of Microsoft Office previous to Office 2007, developers used the CommandBars object model to create the Microsoft Visual Basic® code that modified the UI. In Office 2013, this legacy code continues to work in most cases without modification. However, changes made to toolbars in Office 2003 now appear on an Add-Ins tab in the Office 2013. The type of customization that appears depends on the original design of the add-in. For example, Office creates a Menu Commands group that contains the items that you added to the previous menu structure (File menu, Insert menu, Tools menu, and so forth). It also creates a Toolbar Commands group that contains the items that you added to the previous built-in toolbars (such as the Standard toolbar, Formatting toolbar, and Picture toolbar). In addition, custom toolbars from an add-in or a document appear in the Custom Toolbars group on the Add-Ins tab.

Callback Procedures Add Functionality to the Ribbon

With Ribbon Extensibility, you specify callbacks to update properties and perform actions from your UI at runtime. For example, consider the onAction callback method for a button in the following RibbonX markup. <button id="myButton" onAction="MyButtonOnAction" /> This markup tells Office to call the MyButtonOnAction function when the button is clicked. The MyButtonOnAction function has a specific signature that depends on your choice of languages; here is an example in Microsoft Visual C#.

C# Copy code Copy code
public void MyButtonOnAction (IRibbonControl control)
   {
      if (control.Id=="myButton")
      {
         System.Windows.Forms.MessageBox.Show("Button clicked!");
      }
   }

Customizing the Ribbon with COM Add-Ins

Customization at the application-level results in a modified ribbon that appears in the application no matter which document is open. You create COM add-ins primarily to make these modifications. To customize the ribbon by using COM add-ins, do the following:

  1. Create a COM add-in project. The add-in that you create must implement the Extensibility.IDTExtensibility2 interface that all COM add-ins implement, as well as the IRibbonExtensibility interface that is in the Microsoft.Office.Core namespace.

  2. Build the add-in and setup project, and then install the project.

  3. Start the Office application. When the add-in loads, it triggers the IDTExtensibility2::OnConnection event, which initializes the add-in, just as in previous versions of Office.

  4. Next, the QueryInterface method is called, which determines if the IRibbonExtensibility interface is implemented.

  5. If so, the IRibbonExtensibility::GetCustomUI method is called, which loads the XML markup from the XML customization file or from XML markup embedded in the procedure, and then loads the customizations into the application.

  6. The customized UI is now ready for the user.

Customizing the Ribbon with Office Open XML Formats Files

To customize the UI by using XML markup, do the following:

  1. Create the customization file in any text editor. Add XML markup that adds new components to the ribbon, modifies existing components, or hides components. Save the file as customUI.xml.

  2. Create a folder on your desktop named customUI and copy the customization file to the folder.

  3. Validate the XML markup with custom UI schema.

    Note Note

    This step is optional.

  4. Create a document in the Office application, and then save it as an Open XML Formats file with one of these extensions: .docx, .docm, .xlsx, .xlsm, .pptm, or .pptx. For security, files that contain macros have an m suffix, and can contain procedures that are called by RibbonX commands and controls.

  5. Add a .zip extension to the document file name, and then open the file.

  6. Add the customization file to the container by dragging the folder to the file.

  7. Extract the .rels file that is in the .zip file to your desktop. A _rels folder that contains the .rels file is copied to your desktop.

  8. Open the .rels file and add a line that creates a relationship between the document file and the customization file, and then save the file.

  9. Add the _rels folder back to the container, overwriting the existing file.

  10. Rename the file to its original name by removing the .zip extension. When you open the Office file, the ribbon appears, including your customization to the ribbon.

General Format of XML Markup Files

You can use XML markup to customize the ribbon. The following example shows the general format of an XML markup file that you can use to customize the ribbon in Word 2013.

XML Copy code Copy code
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
  <ribbon>
    <tabs>
      <tab idMso="TabHome">
        <group idMso="GroupFont" visible="false" />
      </tab>
      <tab id="CustomTab" label="My Tab">
        <group id="SampleGroup" label="Sample Group">
          <toggleButton id="ToggleButton1" size="large" label="Large Toggle Button" getPressed="MyToggleMacro"  />
          <checkBox id="CheckBox1" label="A CheckBox" screentip="This is a check box" onAction="MyCheckboxMacro" />
          <editBox id="EditBox1" getText="MyTextMacro" label="My EditBox" onChange="MyEditBoxMacro"/>
          <comboBox id="Combo1" label="My ComboBox" onChange="MyComboBoxMacro">
            <item id="Zip1" label="33455" />
            <item id="Zip2" label="81611" />
            <item id="Zip3" label="31561" />
          </comboBox>
          <advanced>
            <button id="Launcher1" screentip="My Launcher" onAction="MyLauncherMacro" />
          </advanced>
        </group>
        <group id="MyGroup" label="My Group" >
          <button id="Button" label="My Large Button" size="large" onAction="MyButtonMacro" />
          <button id="Button2" label="My Normal Button" size="normal" onAction="MyOtherButtonMacro" />
        </group >
      </tab>
    </tabs>
  </ribbon>
</customUI>

This sample makes the following changes to the ribbon in Word 2013, in the following order:

  1. Declares the default namespace and a custom namespace.

  2. Hides the built-in GroupFont group that is located on the built-in Home tab.

  3. Adds a new CustomTab tab to the right of the last built-in tab.

    Note Note

    Use the id= identifier attribute to create a custom item, such as a custom tab. Use the idMso= identifier attribute to refer to a built-in item, such as the TabHome tab.

  4. Adds a new SampleGroup group to the My Tab tab.

  5. Adds a large-sized ToogleButton1 button to My Group and specifies an onAction callback along with a GetPressed callback.

  6. Adds a CheckBox1 check box to My Group with a custom screentip and specifies an onAction callback.

  7. Adds a EditBox1 edit box to My Group and specifies an onChange callback.

  8. Adds a Combo1 combo box to My Group with three items. The combo box specifies an onChange callback that uses the text from each item.

  9. Adds a Launcher1 launcher to My Group with the onAction callback set. A launcher can also display a custom dialog box to offer more options to the user.

  10. Adds a new MyGroup group to the custom tab.

  11. Adds a large-sized Button1 button to MyGroup and specifies an onAction callback.

  12. Adds a normal-sized Button1 button that is a normal-sized button to MyGroup and specifies an onAction callback.

Working with Legacy Command Bar Add-Ins

When you create COM add-ins, you usually need a way for users to interact with the add-in. In earlier versions of Office, you added a menu item or toolbar button to the application by using the CommandBars object model. In this release of Office, custom applications continue to work in the ribbon without modification in most cases. However, changes that you made with the CommandBars object model, or any other technology that modified the menus or toolbars like WordBasic or XLM, appear on a separate Add-Ins tab. This makes it easier for users to locate the controls.

Dynamically Updating the Ribbon

Callbacks that return properties of a control normally get called one time unless you specify that the call is to be repeated. You can requery your callback by implementing the onLoad callback in the CustomUI element. This callback gets called one time when the RibbonX markup file is successfully loaded, and then passes the code to an IRibbonUI object. The following code example gets the IRibbonUI object so that you can update your controls at runtime.

XML Markup:

<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="ribbonLoaded">

In C#: Write a callback in your Connect class.

C# Copy code Copy code
IRibbonUI myRibbon;

     public void ribbonLoaded(IRibbonUI ribbon) {
         myRibbon = ribbon;
     }

The ribbon gives users a flexible way to work with Office applications. You use simple, text-based, declarative XML markup to create and customize the ribbon. With a few lines of XML, you can create just the right interface for the user. Because the XML markup is in one file, it is easier to modify the interface as requirements change. You can also improve user productivity by placing the commands where users can easily find them. Finally, the ribbon adds consistency across applications, which reduces the time that users spend to learn each application.


Using the Document Inspector

 Copy code hover
[image]

Using the Document Inspector
Send feedback

The Document Inspector gives users an easy way to examine documents for personal or sensitive information, text phrases, or other document contents. They can then use the Document Inspector to remove unwanted information; for example, before they distribute the document.

Note Note

Microsoft does not support the automatic removal of hidden information for signed or protected documents, or for documents that use Information Rights Management (IRM). We recommend that you run the Document Inspector before you sign a document or invoke IRM on a document.

As a developer, you can use the Document Inspector framework to extend the built-in modules and integrate your extensions into the standard user interface.

The Document Inspector in Microsoft Word 2010, Microsoft Excel 2010, and Microsoft PowerPoint 2010 include the following enhancements.

Built-in Document Inspector Modules

The Document Inspector has modules that help users to inspect and fix specific elements of a given document. The Document Inspector in the 2010 Microsoft Office System includes the following built-in modules:

For Excel documents:

  • Comments and Annotations

  • Document Properties and Personal Information

  • Headers and Footers

  • Hidden Rows and Columns

  • Hidden Worksheets

  • Invisible Content

For PowerPoint documents:

  • Comments and Annotations

  • Document Properties and Personal Information

  • Invisible On-Slide Content

  • Off-slide Content

  • Presentation Notes

For Word documents:

  • Comments and Annotations

  • Document Properties and Personal Information

  • Headers and Footers

  • Hidden Rows and Columns

  • Hidden Worksheets

  • Invisible Content

  • Comments and Annotations

  • Document Properties and Personal Information

  • Invisible On-Slide Content

  • Off-slide Content

  • Presentation Notes

  • Comments, Revisions, Versions, and Annotations

  • Document Properties and Personal Information. This includes metadata, Microsoft SharePoint properties, custom properties, and other content information.

  • Custom XML Data

  • Headers, Footers, and Watermarks

  • Invisible Content

  • Hidden Text

For PowerPoint documents:

  • Comments and Annotations

  • Document Properties and Personal Information

  • Invisible On-Slide Content

  • Off-slide Content

  • Presentation Notes

For Word documents:

  • Comments, Revisions, Versions, and Annotations

  • Document Properties and Personal Information. This includes metadata, Microsoft SharePoint properties, custom properties, and other content information.

  • Custom XML Data

  • Headers, Footers, and Watermarks

  • Invisible Content

  • Hidden Text

Opening the Document Inspector

To open the Document Inspector:

  1. Click the BackstageButton tab, and then click Info.

  2. Click Check for Issues.

  3. Click Inspect Document.

Use the Document Inspector dialog box to select the type or types of data to find in the document.

After the modules complete the inspection, the Document Inspector displays the results for each module in a dialog box. If a given module finds data, the dialog box includes a Remove All button that you can click to remove that data. If the module does not find data, the dialog box displays a message to that effect.

If you choose to remove the data for a given module, the dialog box displays descriptive text that indicates whether the operation was successful or not. If the Document Inspector encounters errors during the operation, the module is flagged, displays an error message, and the data for that module does not change.


Security Notes for Microsoft Office Solution Developers

 Copy code hover
[image]

Security Notes for Microsoft Office Solution Developers
Send feedback

Setting Microsoft Office 2013 Security in a Testing Environment

Note Note

You can include Microsoft Visual Basic for Applications (VBA) code or run COM Add-ins only in a macro-enabled document, worksheet, or presentation. You can create a macro-enabled file by saving the documents with a .docm or .dotm extension in Microsoft Word; .xlsm, xltm, or xlam extension in Microsoft Excel; or pptm, potm, ppam, or ppsm extension in Microsoft PowerPoint.

To install and run an unsigned COM add-in, the Require Application Add-ins to be signed by Trusted Publisher and the Disable all Application Add-ins options must be cleared in the Add-ins tab in the Trust Center. To open the Add-ins tab, click the File tab, and then click Options, Trust Center, Trust Center Settings, and Add-ins.

To run all VBA macros, including those that have not been digitally signed, the Enable all macros option must be selected in the Trust Center. To view the Macro Settings options, click the File tab, and then click Options, Trust Center, Trust Center Settings, and Macros Settings. For security reasons, it is strongly recommended that you do this only in a testing environment. After you complete your testing, set the options back to their original state.

On the Macro Settings tab of the Trust Center, you can also set options to Disable all macros without notification, Disable all macros with notification, or Disable all macro except digitally signed macros. You can also disable macros by saving the Word document, Excel worksheet, or PowerPoint presentation as macro-disabled files (.docm, xlsm, or pptm, respectively). You can also set or disable access to the VBA project object model from the Macro Settings tab by selecting or clearing the Trust access to the VBA project object model option.

Note Note

On the Office Fluent user interface ribbon, when COM and application-specific add-ins are enabled and loaded, their controls are displayed on an Add-ins tab.

You can see a list of available add-ins on the Add-ins tab in the Trust Center. On the same tab, you can enable, disable, add, or remove COM or Word add-ins by selecting the type of add-in in the drop-down box by the Manage label and then clicking the Go button.

Modifying the Microsoft Windows Registry

Modifying the Microsoft Windows registry in any manner, whether in the Registry Editor or programmatically, always carries some degree of risk. Incorrect modification can cause serious problems that may require you to reinstall your operating system. It is always a good practice to back up a computer's registry first before you modify it. If you are running Microsoft Windows NT, Microsoft Windows 2000, Microsoft Windows XP, or Microsoft Windows Server 2003, you should also update your Emergency Repair Disk (ERD).

For information about how to edit the registry, see the "Changing Keys and Values" Help topic in the Registry Editor (Regedit.exe) or the "Add and Delete Information in the Registry" and "Edit Registry Information" topics in the Registry Editor (Regedt32.exe).

Making Microsoft Windows Application Programming Interface (API) Function Calls

Before calling Microsoft Windows functions, you should understand how arguments and data types are handled by the Windows API DLLs. Incorrectly calling Windows functions might result in invalid page faults or other unexpected behaviors. For more information about how to call Windows functions, see the topic "The Windows API and Other Dynamic-Link Libraries" in the Microsoft Office 2000 Developer Online Documentation or the Microsoft Developer Network (MSDN) Library.

Digital Code Signing

Digitally signing a document is the process of "stamping" a document so that the recipient of the document can be assured that it came from a particular source, and can detect whether the contents of the document have changed since the document was signed. Additionally, digital signatures can be used to mark a document as read-only to protect its authenticity and integrity.

In addition to digital signatures, documents can also contain in-document signatures that are visible in the document's content. The originator of the document can create unsigned documents with signature lines that can be transmitted to the recipient to sign. The recipient opens the document, locates the signature line, signs the document, and then returns it to the sender.

Basically, the steps to digitally sign a document include:

  1. The document's originator compacts the document's content into a few lines by using a process called "hashing." The compressed content is called a message digest. Hashing is performed by software that is created for that purpose.

  2. The document's originator then encrypts the message digest by using a private key obtained from a signing authority. The result is a digital signature.

  3. The originator attaches the digital signature to the document. All of the data that was hashed has now been signed, and the signature has been encrypted and attached to the document.

  4. The originator then sends the document to the recipient.

  5. The recipient first decrypts the document by using a public key received from the originator. This changes the signature back to a message digest. If this works, it proves that the document was signed by the originator.

  6. The recipient, using digital signing software, hashes the document into a message digest and compares this hash to the hash from the sender. If they match, this verifies that the contents of the document have not changed since the document was sent by the originator.

Digital signatures have been available to customers since Office XP. However, Office 2007 added features that make it easier for users to digitally sign documents, sign their documents to make them read-only, and add inline-document signature lines to a document. Microsoft Office 2013 users can perform these tasks from the Office user interface that is available from the File tab.

Office 2007 also introduced members that make it easier to work with in-line signatures and digital signatures programmatically. For more information, search the MSDN Library for "Office signatures."

Secure Deployment of Managed COM Add-ins in Microsoft Office 2013

To comply with Office 2013 security, managed COM add-ins (COM add-ins targeting the common language runtime) must be digitally signed, and users' security settings should be set in the Office Trust Center to allow add-ins in your Office applications. Additionally, you must incorporate into your managed COM add-in project a small unmanaged proxy called a shim to avoid unexpected security warnings. For details, search for "deployment managed add-ins" in the MSDN Library.

Automating the Visual Basic Editor

In Office 2013, when calling the features of the Microsoft Visual Basic for Applications Extensibility object model, you might receive an error message that programmatic access to the Visual Basic project is not trusted. To prevent this message from appearing, click the File tab, click Options, click the Trust Center tab, and then click Trust Center Settings. Next, click the Macro Settings tab and then select the Trust access to the VBA project object model box. By checking this box, you make it possible for macros in any macro-enabled documents that you open to access the core Microsoft Visual Basic objects, methods, and properties. Setting the option represents a possible security hazard. The recommended behavior is to check the Trust access to the VBA project object model box only for the duration of a macro that accesses the Visual Basic object model. Make sure that you clear the Trust access to the VBA project object model box after the macro has finished running.

Passwords

Avoid using hard-coded passwords in your applications. If a password is required in a procedure, request the password from the user, store it in a variable, and then use the variable in your code.

Always use strong passwords. Strong passwords should contain:

  • Both lowercase and uppercase characters.

  • Numbers.

  • Symbols (such as #, $, %, and ^).

  • At least eight characters.

Strong passwords should not contain patterns, themes, or words found in a dictionary.

Examples of strong passwords include:

  • $tR0n9p@$s

  • G80dn[s$M4!

Note Note

You should change your password frequently; for example, every one to three months.


How do I... (object library reference for Office 2013)

 Copy code hover
[image]

How do I... (object library reference for Office 2013)
Send feedback

This topic lists programming tasks for common Microsoft Office scenarios and provides links to how-to and walkthrough topics that address those tasks. The Microsoft Office Developer Documentation team welcomes your task ideas and code samples. To submit task ideas and code samples, contact us at docthis@microsoft.com.

The following how-to topics provide key task-based procedures for those who want to program and develop applications by using the Microsoft Office Object Library.

  • How to: Customize the Office Fluent Ribbon by Using an Open XML Formats File

  • How to: Customize the Office Fluent Ribbon by Using a Managed COM Add-in

  • How to: Customize the Office Fluent Ribbon by Using a Visual Basic COM Add-in


How to: Customize the Office Fluent Ribbon by Using an Open XML Formats File

 Copy code hover
[image]

How to: Customize the Office Fluent Ribbon by Using an Open XML Formats File
Send feedback

The ribbon component of the Microsoft Office Fluent user interface gives users a flexible way to work with Office applications. Ribbon Extensibility (RibbonX) uses a simple, text-based, declarative XML markup to create and customize the ribbon.

The code example in this topic shows how to add custom components to the ribbon for a single document, as opposed to adding application-level customizations. In the following steps, you add a custom tab, a custom group, and a custom button to the existing ribbon in Microsoft Word. You also implement a callback procedure for the button that inserts a company name into the document.

  1. Create the customization file in any text editor and save the file with the name customUI.xml.

  2. Add the following XML markup to the file and then close and save the file.

    XML Copy code Copy code
    <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
  <ribbon>
    <tabs>
      <tab id="CustomTab" label="My Tab">
        <group id="SampleGroup" label="Sample Group">
          <button id="Button" label="Insert Company Name" size="large" onAction="ThisDocument.InsertCompanyName" />
        </group >
      </tab>
    </tabs>
  </ribbon>
</customUI>

  3. Create a folder on your desktop named customUI and copy the XML customization file to the folder.

  4. Validate the XML markup with a custom schema.

    Note Note

    This step is optional.

  5. Create a document in Word 2007 and save it with the name RibbonSample.docm.

  6. Open the Visual Basic Editor, add the following procedure to the ThisDocument code module, and then close and save the document.

    VBA Copy code Copy code
    Sub InsertCompanyName(ByVal control As IRibbonControl)
   ' Inserts the specified text at the beginning of a range or selection.
   Dim MyText As String
   Dim MyRange As Object
   Set MyRange = ActiveDocument.Range
   MyText = "Microsoft Corporation"
   ' Range Example: Inserts text at the beginning
   ' of the active document
   MyRange.InsertBefore (MyText)
   ' Selection Example:
   'Selection.InsertBefore (MyText)
End Sub

  7. Add a .zip extension to the document file name and then double-click it to open the file.

  8. Add the customization file to the container by dragging the customUI folder from the desktop to the .zip file.

  9. Extract the .rels file to your desktop. A _rels folder that contains the .rels file is copied to your desktop.

  10. Open the .rels file and add the following line between the last Relationship tag and the Relationships tag. This creates a relationship between the document file and the customization file.

    <Relationship Id="someID" Type="http://schemas.microsoft.com/office/2006/relationships/ui/extensibility" Target="customUI/customUI.xml" />

  11. Close and save the file.

  12. Add the _rels folder back to the container file by dragging it from the desktop, overwriting the existing file.

  13. Rename the document file to its original name by removing the .zip extension.

  14. Open the document and notice that the ribbon now displays the My Tab tab.

  15. Click the tab and notice the Sample Group group with a button control.

  16. Click the button to insert the company name into the document.


How to: Customize the Office Fluent Ribbon by Using a Managed COM Add-in

 Copy code hover
[image]

How to: Customize the Office Fluent Ribbon by Using a Managed COM Add-in
Send feedback

The ribbon component of the Microsoft Office Fluent user interface in Microsoft Office suites gives users a flexible way to work with Office applications. Ribbon Extensibility (RibbonX) uses simple, text-based, declarative XML markup to create and customize the ribbon.

The code example in this topic shows how to customize the ribbon in an Office application, no matter what document is open. In the following steps, you create application-level customizations by using a managed COM add-in, and you create the add-in in Microsoft Visual Studio 2012 by using Microsoft Visual C#. The project adds a custom tab, a custom group, and a custom button to the ribbon. To complete the procedure, you perform the following tasks.

  1. Create the XML customization file.

  2. Create a managed COM add-in project in Microsoft Visual Studio 2012 with C#.

  3. Add the XML customization file to the project as an embedded resource.

  4. Implement the IRibbonExtensibility interface.

  5. Create a callback method that is triggered when the button is clicked.

  6. Build, install, and test the project.

Create the XML Customization File

In this step, you create the file that adds the custom components to the ribbon.

  1. In a text editor, add the following XML markup.

    XML Copy code Copy code
    <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
  <ribbon>
    <tabs>
      <tab id="CustomTab" label="My Tab">
        <group id="SampleGroup" label="Sample Group">
          <button id="Button" label="Insert Company Name" size="large" onAction="InsertCompanyName" />
        </group >
      </tab>
    </tabs>
  </ribbon>
</customUI>

  2. Close and save the file as customUI.xml.

Create the Managed COM Add-in Project

In this step, you create a COM add-in C# project in Microsoft Visual Studio 2012.

  1. Start Microsoft Visual Studio 2012.

  2. On the File menu, click New Project.

  3. In the New Project dialog box under Project Types, expand Other Projects, click Extensibility Projects, and then double-click Shared Addin.

  4. Add a name for the project; for this sample, type RibbonXSampleCS.

  5. In the first screen of the Shared Add-in Wizard, click Next.

  6. Select Create an Add-in using Visual C#, and then click Next.

  7. Clear all of the selections except Microsoft Word and then click Next.

  8. Type a name and description for the add-in, and then click Next.

  9. In the Choose Add-in Options screen, select I would like my Add-in to load when the host application loads and then click Next.

  10. Click Finish to complete the wizard.

Add External References to the Project

In this step you add references to the Word Primary Interop Assemblies and type library.

  1. In the Solution Explorer, right-click References, and then click Add Reference.

    Note Note

    If you do not see the References folder, click the Project menu and then click Show All Files.

  2. Scroll down on the .NET tab, press the CTRL key, and then select Microsoft.Office.Interop.Word.

  3. On the COM tab, scroll down, select either the Microsoft Office 15.0 Object Library (or the library that is appropriate for your version of Office), and then click OK.

  4. Add the following namespace references to the project, if they do not already exist, just below the namespace line.

    C# Copy code Copy code
    using System.Reflection;
using Microsoft.Office.Core;
using System.IO;
using System.Xml;
using Extensibility;
using System.Runtime.InteropServices;
using MSword = Microsoft.Office.Interop.Word;

Add the Customization File as an Embedded Resource

In this step, you add the XML customization file as an embedded resource in the project.

  1. In the Solution Explorer, right-click RibbonXSampleCS, point to Add, and click Existing Item.

  2. Navigate to the customUI.xml file that you created, select the file, and then click Add.

  3. In the Solution Explorer, right-click customUI.xml, and then select Properties.

  4. In the Property window select Build Action, and then scroll down to Embedded Resource.

Implement the IRibbonExtensibility Interface

In this step you add code to the Extensibility.IDTExtensibility2::OnConnection to create a reference to the Word application at runtime. You also implement the only member of the IRibbonExtensibility interface, GetCustomUI.

  1. In the Solution Explorer, right-click Connect.cs, and click View Code.

  2. After the Connect method, add the following declaration, which creates a reference to the Word Application object:

    private MSword.Application applicationObject;

  3. Add the following line to the OnConnection method. This statement creates an instance of the Word Application object:

    applicationObject =(MSword.Application)application;

  4. At the end of the public class Connect statement, add a comma, and then type IRibbonExtensibility.

    Note Note

    You can use Microsoft IntelliSense to insert interface methods for you. For example, at the end of the public class Connect: statement, type IRibbonExtensibility, right-click and point to Implement Interface, and then click Implement Interface Explicitly. This adds a stub for the GetCustomUI method. The implementation looks similar to the following code.

    C# Copy code Copy code
    string IRibbonExtensibility.GetCustomUI(string RibbonID)
{
}

  5. Insert the following statement into the GetCustomUI method, overwriting the existing code.return GetResource("customUI.xml");

  6. Insert the following method below the GetCustommUI method:

    C# Copy code Copy code
    private string GetResource(string resourceName)
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            foreach (string name in asm.GetManifestResourceNames())
            {
                if (name.EndsWith(resourceName))
                {
                    System.IO.TextReader tr = new System.IO.StreamReader(asm.GetManifestResourceStream(name));
                    //Debug.Assert(tr != null);
                    string resource = tr.ReadToEnd();

                    tr.Close();
                    return resource;
                }
            }
            return null;
        }

    The GetCustomUI method calls the GetResource method. The GetResource method sets a reference to this assembly during runtime and then loops through the embedded resource until it finds the one named customUI.xml. It then creates an instance of the StreamReader object that reads the embedded file containing the XML markup. The procedure passes the XML back to the GetCustomUI method which returns the XML to the ribbon. Alternately, you can construct a string that contains the XML markup and read it directly into the GetCustomUI method.

  7. Following the GetResource method, add this method. This method inserts the company name into the document at the beginning of the page.

    C# Copy code Copy code
    public void InsertCompanyName(IRibbonControl control)
        {
        // Inserts the specified text at the beginning of a range or selection.
            string MyText;
            MyText = "Microsoft Corporation";

            MSword.Document doc = applicationObject.ActiveDocument;

            //Inserts text at the beginning of the active document.
            object startPosition = 0;
            object endPosition = 0;
            MSword.Range r = (MSword.Range)doc.Range(
                   ref startPosition, ref endPosition);
            r.InsertAfter(MyText);
        }

Build and Install the Project

In this step, you build the add-in and its setup project. Before you continue, make sure that Word is closed.

  1. In the Project menu, click Build Solution. When the build is complete, a notification appears in the lower left corner of the window.

  2. In the Solution Explorer, right-click RibbonXSampleCSSetup and click Build.

  3. Right-click RibbonXSampleCSSetup again and click Install to begin the RibbonXSampleCSSetup Setup Wizard.

  4. Click Next in each of the screens and then click Close on the final screen.

  5. Start Word. You should see the My Tab tab to the right of the other tabs.

Test the Project

Click the My Tab tab and then click Insert Company Name to insert the company name into the document at the cursor. If you do not see the customized ribbon, you might need to add an entry to the Windows registry by completing the following steps.

Caution note Caution

The next few steps contain information about how to modify the registry. Before you modify the registry, be sure to back it up and make sure that you understand how to restore the registry if a problem occurs. For more information about how to back up, restore, and edit the registry, search for the following article in the Microsoft Knowledge Base: 256986 Description of the Microsoft Windows Registry.

  1. In the Solution Explorer, right-click the setup project, RibbonXSampleCSSetup, point to View, and then click Registry.

  2. From the Registry tab, navigate to the following registry key for the add-in: HKCU\Software\Microsoft\Office\Word\AddIns\RibbonXSampleCS.Connect

    Note Note

    If the RibbonXSampleCS.Connect key does not exist, you can create it. To do so, right-click the Addins folder, point to New, and then click Key. Name the key RibbonXSampleCS.Connect. Add a LoadBehavior DWord and set its value to 3.


Reference (object library reference for Office 2013)

 Copy code hover
[image]

Reference (object library reference for Office 2013)
Send feedback

This section of the object library for Microsoft Office 2010 contains documentation for all of the objects, properties, methods, and events contained in the Office object model.

You can use the table of contents to navigate through the documentation.


BulletFormat2 Object (Office)

 Copy code hover
[image]

BulletFormat2 Object (Office)
See also Send feedback

Published: June 15, 2012

Represents bullet formatting.

Example

The following example sets the bullet size and color for the paragraphs in shape two on slide one in the active PowerPoint presentation.

VBA Copy code Copy code
With ActivePresentation.Slides(1).Shapes(2)
 With .TextFrame.TextRange.ParagraphFormat.BulletFormat2
 .Visible = True
 .RelativeSize = 1.25
 .Character = 169
 With .Font
 .Color.RGB = RGB(255, 255, 0)
 .Name = "Symbol"
 End With
 End With
End With

See also

Concepts

Object Model Reference

Other resources

BulletFormat2 Object Members


BulletFormat2 Members (Office)

 Copy code hover
[image]

BulletFormat2 Members (Office)
Send feedback

Published: June 15, 2012

Represents bullet formatting.

Methods

Name | Description
Picture | Sets the graphics file to be used for bullets in a bulleted list.

Properties

Name | Description
Application | Gets an object that represents the BulletFormat2 object. Read-only.
Character | Gets or sets the Unicode character value that is used for bullets in the specified text. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the BulletFormat2 object was created. Read-only.
Font | Gets a Font2 object that represents character formatting for a BulletFormat2 object. Read-only.
Number | Gets the bullet number of a paragraph. Read-only.
Parent | Gets the parent of the BulletFormat2 object. Read-only.
RelativeSize | Returns or sets the bullet size relative to the size of the first text character in the paragraph. Read/write.
StartValue | Gets or sets the beginning value of a bulleted list. Read/write.
Style | Returns or sets a constant that represents the style of a bullet. Read/write.
Type | Gets or sets a constant that represents the type of bullet. Read/write.
UseTextColor | Determines whether the specified bullets are set to the color of the first text character in the paragraph. Read/write.
UseTextFont | Determines whether the specified bullets are set to the font of the first text character in the paragraph. Read/write.
Visible | Gets or sets a value that specifies whether the bullet is visible. Read/write.


BulletFormat2 Properties (Office)

 Copy code hover
[image]

BulletFormat2 Properties (Office)
Send feedback

Published: June 15, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an object that represents the BulletFormat2 object. Read-only.
Character | Gets or sets the Unicode character value that is used for bullets in the specified text. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the BulletFormat2 object was created. Read-only.
Font | Gets a Font2 object that represents character formatting for a BulletFormat2 object. Read-only.
Number | Gets the bullet number of a paragraph. Read-only.
Parent | Gets the parent of the BulletFormat2 object. Read-only.
RelativeSize | Returns or sets the bullet size relative to the size of the first text character in the paragraph. Read/write.
StartValue | Gets or sets the beginning value of a bulleted list. Read/write.
Style | Returns or sets a constant that represents the style of a bullet. Read/write.
Type | Gets or sets a constant that represents the type of bullet. Read/write.
UseTextColor | Determines whether the specified bullets are set to the color of the first text character in the paragraph. Read/write.
UseTextFont | Determines whether the specified bullets are set to the font of the first text character in the paragraph. Read/write.
Visible | Gets or sets a value that specifies whether the bullet is visible. Read/write.


BulletFormat2.Application Property (Office)

 Copy code hover
[image]

BulletFormat2.Application Property (Office)
See also Send feedback

Published: June 15, 2012

Gets an object that represents the BulletFormat2 object. Read-only.

Syntax

expression .Application

expression An expression that returns a BulletFormat2 object.

Return Value

Object

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.Character Property (Office)

 Copy code hover
[image]

BulletFormat2.Character Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the Unicode character value that is used for bullets in the specified text. Read/write.

Syntax

expression .Character

expression An expression that returns a BulletFormat2 object.

Return Value

Integer

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.Creator Property (Office)

 Copy code hover
[image]

BulletFormat2.Creator Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a 32-bit integer that indicates the application in which the BulletFormat2 object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a BulletFormat2 object.

Return Value

Long

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.Font Property (Office)

 Copy code hover
[image]

BulletFormat2.Font Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a Font2 object that represents character formatting for a BulletFormat2 object. Read-only.

Syntax

expression .Font

expression An expression that returns a BulletFormat2 object.

Return Value

Font2

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.Number Property (Office)

 Copy code hover
[image]

BulletFormat2.Number Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the bullet number of a paragraph. Read-only.

Syntax

expression .Number

expression An expression that returns a BulletFormat2 object.

Return Value

Integer

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.Parent Property (Office)

 Copy code hover
[image]

BulletFormat2.Parent Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the parent of the BulletFormat2 object. Read-only.

Syntax

expression .Parent

expression An expression that returns a BulletFormat2 object.

Return Value

Object

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.RelativeSize Property (Office)

 Copy code hover
[image]

BulletFormat2.RelativeSize Property (Office)
See also Send feedback

Published: June 15, 2012

Returns or sets the bullet size relative to the size of the first text character in the paragraph. Read/write.

Syntax

expression .RelativeSize

expression An expression that returns a BulletFormat2 object.

Return Value

Single

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.StartValue Property (Office)

 Copy code hover
[image]

BulletFormat2.StartValue Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the beginning value of a bulleted list. Read/write.

Syntax

expression .StartValue

expression An expression that returns a BulletFormat2 object.

Return Value

Integer

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.Style Property (Office)

 Copy code hover
[image]

BulletFormat2.Style Property (Office)
See also Send feedback

Published: June 15, 2012

Returns or sets a constant that represents the style of a bullet. Read/write.

Syntax

expression .Style

expression An expression that returns a BulletFormat2 object.

Return Value

MsoNumberedBulletStyle

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.Type Property (Office)

 Copy code hover
[image]

BulletFormat2.Type Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets a constant that represents the type of bullet. Read/write.

Syntax

expression .Type

expression An expression that returns a BulletFormat2 object.

Return Value

MsoBulletType

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.UseTextColor Property (Office)

 Copy code hover
[image]

BulletFormat2.UseTextColor Property (Office)
See also Send feedback

Published: June 15, 2012

Determines whether the specified bullets are set to the color of the first text character in the paragraph. Read/write.

Syntax

expression .UseTextColor

expression An expression that returns a BulletFormat2 object.

Return Value

MsoTriState

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.UseTextFont Property (Office)

 Copy code hover
[image]

BulletFormat2.UseTextFont Property (Office)
See also Send feedback

Published: June 15, 2012

Determines whether the specified bullets are set to the font of the first text character in the paragraph. Read/write.

Syntax

expression .UseTextFont

expression An expression that returns a BulletFormat2 object.

Return Value

MsoTriState

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2.Visible Property (Office)

 Copy code hover
[image]

BulletFormat2.Visible Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets a value that specifies whether the bullet is visible. Read/write.

Syntax

expression .Visible

expression An expression that returns a BulletFormat2 object.

Return Value

MsoTriState

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


BulletFormat2 Methods (Office)

 Copy code hover
[image]

BulletFormat2 Methods (Office)
Send feedback

Published: June 15, 2012

This object has the following methods:

Methods

Name | Description
Picture | Sets the graphics file to be used for bullets in a bulleted list.


BulletFormat2.Picture Method (Office)

 Copy code hover
[image]

BulletFormat2.Picture Method (Office)
See also Send feedback

Published: June 15, 2012

Sets the graphics file to be used for bullets in a bulleted list.

Syntax

expression .Picture(FileName)

expression An expression that returns a BulletFormat2 object.

Parameters

Name | Required/Optional | Data Type | Description
FileName | Required | String | The file name of a valid graphics file.

Remarks

Valid graphics files include files with the following extensions: .bmp, .cdr, .cgm, .drw, .dxf, .emf, .eps, .gif, .jpg, .jpeg, .pcd, .pct, .pcx, .pict, .png, .tga, .tiff, .wmf, and .wpg.

See also

Concepts

BulletFormat2 Object

Other resources

BulletFormat2 Object Members


COMAddIn Object (Office)

 Copy code hover
[image]

COMAddIn Object (Office)
See also Send feedback

Published: June 15, 2012

Represents a COM add-in in the Microsoft Office host application. The COMAddIn object is a member of the COMAddIns collection.

Example

Use COMAddIns.Item(index), where index is either an ordinal value that returns the COM add-in at that position in the COMAddIns collection, or a String value that represents the ProgID of the specified COM add-in. The following example displays a COM add-in's description text in a message box.

Copy code Copy code
MsgBox Application.COMAddIns.Item("msodraa9.ShapeSelect").Description

Use the ProgID property of the COMAddin object to return the programmatic identifier for a COM add-in, and use the Guid property to return the globally unique identifier (GUID) for the add-in. The following example displays the ProgID and GUID for COM add-in one in a message box.

Copy code Copy code
MsgBox "My ProgID is " & _
 Application.COMAddIns(1).ProgID & _
 " and my GUID is " & _
 Application.COMAddIns(1).Guid

Use the Connect property to set or return the state of the connection to a specified COM add-in. The following example displays a message box that indicates whether COM add-in one is registered and currently connected.

Copy code Copy code
If Application.COMAddIns(1).Connect Then
 MsgBox "The add-in is connected."
Else
MsgBox "The add-in is not connected."
End If

See also

Concepts

Object Model Reference

Other resources

COMAddIn Object Members


COMAddIn Members (Office)

 Copy code hover
[image]

COMAddIn Members (Office)
Send feedback

Published: June 15, 2012

Represents a COM add-in in the Microsoft Office host application. The COMAddIn object is a member of the COMAddIns collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the COMAddIn object (you can use this property with an Automation object to return that object's container application). Read-only.
Connect | Gets or sets the state of the connection for the specified COMAddIn object. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the COMAddIn object was created. Read-only.
Description | Gets or sets a descriptive String value for the specified COMAddin object. Read/write.
Guid | Gets the class identifier (CLSID) for the specified COMAddIn object. Read-only.
Object | Gets or sets an object reference. Read/write.
Parent | Gets the Parent object for the COMAddIn object. Read-only.
ProgId | Gets the programmatic identifier (ProgID) for the specified COMAddIn object. Read-only.


COMAddIn Properties (Office)

 Copy code hover
[image]

COMAddIn Properties (Office)
Send feedback

Published: June 15, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the COMAddIn object (you can use this property with an Automation object to return that object's container application). Read-only.
Connect | Gets or sets the state of the connection for the specified COMAddIn object. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the COMAddIn object was created. Read-only.
Description | Gets or sets a descriptive String value for the specified COMAddin object. Read/write.
Guid | Gets the class identifier (CLSID) for the specified COMAddIn object. Read-only.
Object | Gets or sets an object reference. Read/write.
Parent | Gets the Parent object for the COMAddIn object. Read-only.
ProgId | Gets the programmatic identifier (ProgID) for the specified COMAddIn object. Read-only.


COMAddIn.Application Property (Office)

 Copy code hover
[image]

COMAddIn.Application Property (Office)
See also Send feedback

Published: June 15, 2012

Gets an Application object that represents the container application for the COMAddIn object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a COMAddIn object.

Return Value

Object

See also

Concepts

COMAddIn Object

Other resources

COMAddIn Object Members


COMAddIn.Connect Property (Office)

 Copy code hover
[image]

COMAddIn.Connect Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the state of the connection for the specified COMAddIn object. Read/write.

Syntax

expression .Connect

expression A variable that represents a COMAddIn object.

Remarks

The Connect property returns True if the add-in is active; it returns False if the add-in is inactive. An active add-in is registered and connected; an inactive add-in is registered but not currently connected.

Example

The following example displays a message box that indicates whether COM add-in one is registered and currently connected.

Copy code Copy code
If Application.COMAddIns(1).Connect Then
 MsgBox "The add-in is connected."
Else
 MsgBox "The add-in is not connected."
End If

See also

Concepts

COMAddIn Object

Other resources

COMAddIn Object Members


COMAddIn.Creator Property (Office)

 Copy code hover
[image]

COMAddIn.Creator Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a 32-bit integer that indicates the application in which the COMAddIn object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a COMAddIn object.

Return Value

Long

See also

Concepts

COMAddIn Object

Other resources

COMAddIn Object Members


COMAddIn.Description Property (Office)

 Copy code hover
[image]

COMAddIn.Description Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets a descriptive String value for the specified COMAddin object. Read/write.

Syntax

expression .Description

expression Required. A variable that represents a COMAddIn object.

Example

The following example displays the description text of the Microsoft Accessibility COM add-in for drawing.

VBA Copy code Copy code
MsgBox "The description of this " & _
 "COMAddIn is """ & Application.COMAddIns. _
 Item("msodraa9.ShapeSelect"). _
 Description & """

See also

Concepts

COMAddIn Object

Other resources

COMAddIn Object Members


COMAddIn.Guid Property (Office)

 Copy code hover
[image]

COMAddIn.Guid Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the class identifier (CLSID) for the specified COMAddIn object. Read-only.

Syntax

expression .Guid

expression A variable that represents a COMAddIn object.

Example

The following example displays the ProgID and CLSID for the first COM add-in in the COMAddIns collection in a message box.

Copy code Copy code
MsgBox "My ProgID is " & _
 Application.COMAddIns(1).ProgID & _
 " and my CLSID is " & _
 Application.COMAddIns(1).Guid

See also

Concepts

COMAddIn Object

Other resources

COMAddIn Object Members


COMAddIn.Object Property (Office)

 Copy code hover
[image]

COMAddIn.Object Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets an object reference. Read/write.

Syntax

expression .Object

expression A variable that represents a COMAddIn object.

Remarks

The Object property is a read/write property in which any object reference can be stored. In this regard, it is similar to the general-purpose Tag property of certain ActiveX controls.

In some cases, the Object property returns the object represented by the specified COMAddIn object; otherwise, it returns Nothing by default.

Example

The following example returns the object represented by the COM add-in msodraa9.ShapeSelect.

Copy code Copy code
Dim objBaseObject As Object
Set objBaseObject = _
 Application.COMAddIns.Item("msodraa9.ShapeSelect").Object

See also

Concepts

COMAddIn Object

Other resources

COMAddIn Object Members


COMAddIn.Parent Property (Office)

 Copy code hover
[image]

COMAddIn.Parent Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the Parent object for the COMAddIn object. Read-only.

Syntax

expression .Parent

expression A variable that represents a COMAddIn object.

Return Value

Object

See also

Concepts

COMAddIn Object

Other resources

COMAddIn Object Members


COMAddIn.ProgId Property (Office)

 Copy code hover
[image]

COMAddIn.ProgId Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the programmatic identifier (ProgID) for the specified COMAddIn object. Read-only.

Syntax

expression .ProgId

expression A variable that represents a COMAddIn object.

Example

The following example displays the ProgID and GUID for COM add-in one in a message box.

Copy code Copy code
MsgBox "My ProgID is " & _
 Application.COMAddIns(1).ProgID & _
 " and my GUID is " & _
 Application.COMAddIns(1).Guid

See also

Concepts

COMAddIn Object

Other resources

COMAddIn Object Members


COMAddIns Object (Office)

 Copy code hover
[image]

COMAddIns Object (Office)
See also Send feedback

Published: June 15, 2012

A collection of COMAddIn objects that provide information about a COM add-in registered in the Windows registry.

Example

Use the COMAddIns property of the Application object to return the COMAddIns collection for a Microsoft Office host application. This collection contains all of the COM add-ins that are available to a given Office host application, and the Count property of the COMAddins collection returns the number of available COM add-ins, as in the following example.

Copy code Copy code
MsgBox Application.COMAddIns.Count

Use the Update method of the COMAddins collection to refresh the list of COM add-ins from the Windows registry, as in the following example.

Copy code Copy code
Application.COMAddIns.Update

Use COMAddIns.Item(index), where index is either an ordinal value that returns the COM add-in at that position in the COMAddIns collection, or a String value that represents the ProgID of the specified COM add-in. The following example displays a COM add-in's description text and ProgID ("msodraa9.ShapeSelect") in a message box.

Copy code Copy code
MsgBox Application.COMAddIns.Item("msodraa9.ShapeSelect").Description

See also

Concepts

Object Model Reference

Other resources

COMAddIns Object Members


COMAddIns Members (Office)

 Copy code hover
[image]

COMAddIns Members (Office)
Send feedback

Published: June 15, 2012

A collection of COMAddIn objects that provide information about a COM add-in registered in the Windows registry.

Methods

Name | Description
Item | Gets a member of the specified COMAddIns collection.
Update | Updates the contents of the COMAddIns collection from the list of add-ins stored in the Windows registry.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the COMAddIns object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a count of the number of COM add-ins in the host application. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the COMAddIns object was created. Read-only.
Parent | Gets the Parent object for the COMAddIns object. Read-only.


COMAddIns Properties (Office)

 Copy code hover
[image]

COMAddIns Properties (Office)
Send feedback

Published: June 15, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the COMAddIns object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a count of the number of COM add-ins in the host application. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the COMAddIns object was created. Read-only.
Parent | Gets the Parent object for the COMAddIns object. Read-only.


COMAddIns.Application Property (Office)

 Copy code hover
[image]

COMAddIns.Application Property (Office)
See also Send feedback

Published: June 15, 2012

Gets an Application object that represents the container application for the COMAddIns object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a COMAddIns object.

Return Value

Object

See also

Concepts

COMAddIns Object

Other resources

COMAddIns Object Members


COMAddIns.Count Property (Office)

 Copy code hover
[image]

COMAddIns.Count Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a count of the number of COM add-ins in the host application. Read-only.

Syntax

expression .Count

expression An expression that returns a COMAddIns object.

Return Value

Long

See also

Concepts

COMAddIns Object

Other resources

COMAddIns Object Members


COMAddIns.Creator Property (Office)

 Copy code hover
[image]

COMAddIns.Creator Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a 32-bit integer that indicates the application in which the COMAddIns object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a COMAddIns object.

Return Value

Long

See also

Concepts

COMAddIns Object

Other resources

COMAddIns Object Members


COMAddIns.Parent Property (Office)

 Copy code hover
[image]

COMAddIns.Parent Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the Parent object for the COMAddIns object. Read-only.

Syntax

expression .Parent

expression A variable that represents a COMAddIns object.

Return Value

Object

See also

Concepts

COMAddIns Object

Other resources

COMAddIns Object Members


COMAddIns Methods (Office)

 Copy code hover
[image]

COMAddIns Methods (Office)
Send feedback

Published: June 15, 2012

This object has the following methods:

Methods

Name | Description
Item | Gets a member of the specified COMAddIns collection.
Update | Updates the contents of the COMAddIns collection from the list of add-ins stored in the Windows registry.


COMAddIns.Item Method (Office)

 Copy code hover
[image]

COMAddIns.Item Method (Office)
See also Send feedback

Published: June 15, 2012

Gets a member of the specified COMAddIns collection.

Syntax

expression .Item(Index)

expression Required. A variable that represents a COMAddIns object. The specified COMAddIns collection.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | Represents the location of the member within the collection.

See also

Concepts

COMAddIns Object

Other resources

COMAddIns Object Members


COMAddIns.Update Method (Office)

 Copy code hover
[image]

COMAddIns.Update Method (Office)
See also Send feedback

Published: June 15, 2012

Updates the contents of the COMAddIns collection from the list of add-ins stored in the Windows registry.

Syntax

expression .Update

expression A variable that represents a COMAddIns object.

Remarks

Before you can use a given COM add-in in a Microsoft Office application, that add-in must be registered in the Windows registry as a COM component with a corresponding Component Category ID. Normally the setup program for a COM add-in will add the necessary entries to the registry.

Example

The following example updates the contents of the COMAddIns collection from the list of add-ins stored in the Windows registry.

Copy code Copy code
Application.COMAddIns.Update

See also

Concepts

COMAddIns Object

Other resources

COMAddIns Object Members


CommandBar Object (Office)

 Copy code hover
[image]

CommandBar Object (Office)
See also Send feedback

Published: June 15, 2012

Represents a command bar in the container application. The CommandBar object is a member of the CommandBars collection.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Example

Use CommandBars(index), where index is the name or index number of a command bar, to return a single CommandBar object. The following example steps through the collection of command bars to find the command bar named "Forms." If it finds this command bar, the example makes it visible and protects its docking state. In this example, the variable cb represents a CommandBar object.

Copy code Copy code
foundFlag = False
For Each cb In CommandBars
    If cb.Name = "Forms" Then
        cb.Protection = msoBarNoChangeDock
        cb.Visible = True
        foundFlag = True
    End If
Next cb
If Not foundFlag Then
    MsgBox "The collection does not contain a Forms command bar."
End If

You can use a name or index number to specify a menu bar or toolbar in the list of available menu bars and toolbars in the container application. However, you must use a name to specify a menu, shortcut menu, or submenu (all of which are represented by CommandBar objects). This example adds a new menu item to the bottom of the Tools menu. When clicked, the new menu item runs the procedure named "qtrReport."

Copy code Copy code
Set newItem = CommandBars("Tools").Controls.Add(Type:=msoControlButton)
With newItem
    .BeginGroup = True
    .Caption = "Make Report"
    .FaceID = 0
    .OnAction = "qtrReport"
End With

If two or more custom menus or submenus have the same name, CommandBars(index) returns the first one. To ensure that you return the correct menu or submenu, locate the pop-up control that displays that menu. Then apply the CommandBar property to the pop-up control to return the command bar that represents that menu. Assuming that the third control on the toolbar named "Custom Tools" is a pop-up control, this example adds the Save command to the bottom of that menu.

Copy code Copy code
Set viewMenu = CommandBars("Custom Tools").Controls(3)
viewMenu.Controls.Add ID:=3    'ID of Save command is 3

See also

Concepts

Object Model Reference

Other resources

CommandBar Object Members


CommandBar Members (Office)

 Copy code hover
[image]

CommandBar Members (Office)
Send feedback

Published: June 15, 2012

Represents a command bar in the container application. The CommandBar object is a member of the CommandBars collection.

Methods

Name | Description
Delete | Deletes the CommandBar object from the collection.
FindControl | Gets a CommandBarControl object that fits a specified criteria.
Reset | Resets a built-in command bar to its default configuration.
ShowPopup | Displays a command bar as a shortcut menu at the specified coordinates or at the current pointer coordinates.

Properties

Name | Description
AdaptiveMenu | Gets a Boolean value that specifies whether the command bar should include an adaptive menu. Read/write.
Application | Gets an Application object that represents the container application for the CommandBar object (you can use this property with an Automation object to return that object's container application). Read-only.
BuiltIn | Gets True if the specified command bar is a built-in command bar of the container application. Returns False if it is a custom command bar. Read-only.
Context | Gets or sets a string that determines where a command bar will be saved. The string is defined and interpreted by the application. Read/write.
Controls | Gets a CommandBarControls object that represents all the controls on a command bar. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBar object was created. Read-only.
Enabled | Gets or sets a Boolean value that specifies whether the specified CommandBar is enabled. Read/write.
Height | Gets or sets the height of a CommandBar. Read/write.
Index | Gets a Long representing the index number for a CommandBar object in the collection. Read-only.
Left | Sets or gets the horizontal distance (in pixels) of the CommandBar from the left edge of the object relative to the screen. Read/write.
Name | Gets the name of the built-in CommandBar object. Read-only.
NameLocal | Gets the name of a built-in command bar as it's displayed in the language version of the container application, or returns or sets the name of a custom command bar. Read/write.
Parent | Gets the Parent object for the CommandBar object. Read-only.
Position | Gets or sets a MsoBarPosition constant representing the position of a command bar. Read/write.
Protection | Gets or sets a MsoBarProtection constant representing the way a command bar is protected from user customization. Read/write.
RowIndex | Gets or sets the docking order of a command bar in relation to other command bars in the same docking area. Can be an integer greater than zero, or either of the following MsoBarRow constants: msoBarRowFirst or msoBarRowLast. Read/write.
Top | Sets or gets the distance from the top edge of the specified command bar, to the top edge of the screen. For docked command bars, this property returns or sets the distance from the command bar to the top of the docking area. Read/write.
Type | Gets the type of command bar. Read-only.
Visible | Gets or sets the Visible property of the command bar. True if the command bar is visible. Read/write.
Width | Gets or sets the width (in pixels) of the specified command bar. Read/write.


CommandBar Properties (Office)

 Copy code hover
[image]

CommandBar Properties (Office)
Send feedback

Published: June 15, 2012

This object has the following properties:

Properties

Name | Description
AdaptiveMenu | Gets a Boolean value that specifies whether the command bar should include an adaptive menu. Read/write.
Application | Gets an Application object that represents the container application for the CommandBar object (you can use this property with an Automation object to return that object's container application). Read-only.
BuiltIn | Gets True if the specified command bar is a built-in command bar of the container application. Returns False if it is a custom command bar. Read-only.
Context | Gets or sets a string that determines where a command bar will be saved. The string is defined and interpreted by the application. Read/write.
Controls | Gets a CommandBarControls object that represents all the controls on a command bar. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBar object was created. Read-only.
Enabled | Gets or sets a Boolean value that specifies whether the specified CommandBar is enabled. Read/write.
Height | Gets or sets the height of a CommandBar. Read/write.
Index | Gets a Long representing the index number for a CommandBar object in the collection. Read-only.
Left | Sets or gets the horizontal distance (in pixels) of the CommandBar from the left edge of the object relative to the screen. Read/write.
Name | Gets the name of the built-in CommandBar object. Read-only.
NameLocal | Gets the name of a built-in command bar as it's displayed in the language version of the container application, or returns or sets the name of a custom command bar. Read/write.
Parent | Gets the Parent object for the CommandBar object. Read-only.
Position | Gets or sets a MsoBarPosition constant representing the position of a command bar. Read/write.
Protection | Gets or sets a MsoBarProtection constant representing the way a command bar is protected from user customization. Read/write.
RowIndex | Gets or sets the docking order of a command bar in relation to other command bars in the same docking area. Can be an integer greater than zero, or either of the following MsoBarRow constants: msoBarRowFirst or msoBarRowLast. Read/write.
Top | Sets or gets the distance from the top edge of the specified command bar, to the top edge of the screen. For docked command bars, this property returns or sets the distance from the command bar to the top of the docking area. Read/write.
Type | Gets the type of command bar. Read-only.
Visible | Gets or sets the Visible property of the command bar. True if the command bar is visible. Read/write.
Width | Gets or sets the width (in pixels) of the specified command bar. Read/write.


CommandBar.AdaptiveMenu Property (Office)

 Copy code hover
[image]

CommandBar.AdaptiveMenu Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a Boolean value that specifies whether the command bar should include an adaptive menu. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .AdaptiveMenu

expression An expression that returns a CommandBar object.

Return Value

Boolean

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Application Property (Office)

 Copy code hover
[image]

CommandBar.Application Property (Office)
See also Send feedback

Published: June 15, 2012

Gets an Application object that represents the container application for the CommandBar object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Application

expression A variable that represents a CommandBar object.

Return Value

Object

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.BuiltIn Property (Office)

 Copy code hover
[image]

CommandBar.BuiltIn Property (Office)
See also Send feedback

Published: June 15, 2012

Gets True if the specified command bar is a built-in command bar of the container application. Returns False if it is a custom command bar. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .BuiltIn

expression A variable that represents a CommandBar object.

Return Value

Boolean

Example

This example deletes all custom command bars that aren't visible.

Copy code Copy code
foundFlag = False
deletedBars = 0
For Each bar In CommandBars
    If (bar.BuiltIn = False) And (bar.Visible = False) Then
        bar.Delete
        foundFlag = True
        deletedBars = deletedBars + 1
    End If
Next
If Not foundFlag Then
    MsgBox "No command bars have been deleted."
Else
    MsgBox deletedBars & " custom command bar(s) deleted."
End If

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Context Property (Office)

 Copy code hover
[image]

CommandBar.Context Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets a string that determines where a command bar will be saved. The string is defined and interpreted by the application. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Context

expression A variable that represents a CommandBar object.

Remarks

You can set the Context property only for custom command bars. This property will fail if the application doesn't recognize the context string, or if the application doesn't support changing context strings programmatically.

Example

This example displays a message box containing the context string for the command bar named "Custom". This example works in Microsoft Word and other applications that support the Context property.

Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
With myBar
    .Controls.Add Type:=msoControlButton, ID:=2
    .Visible = True
End With
MsgBox (myBar.Context)

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Controls Property (Office)

 Copy code hover
[image]

CommandBar.Controls Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a CommandBarControls object that represents all the controls on a command bar. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Controls

expression A variable that represents a CommandBar object.

Return Value

CommandBarControls

Example

This example adds a combo box control to the command bar named "Custom" and fills the list with two items. The example also sets the number of line items, the width of the combo box, and an empty default for the combo box.

VBA Copy code Copy code
Set myControl = CommandBars("Custom").Controls _
    .Add(Type:=msoControlComboBox, Before:=1)
With myControl
    .AddItem Text:="First Item", Index:=1
    .AddItem Text:="Second Item", Index:=2
    .DropDownLines = 3
    .DropDownWidth = 75
    .ListHeaderCount = 0
End With

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Creator Property (Office)

 Copy code hover
[image]

CommandBar.Creator Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a 32-bit integer that indicates the application in which the CommandBar object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a CommandBar object.

Return Value

Long

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Enabled Property (Office)

 Copy code hover
[image]

CommandBar.Enabled Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets a Boolean value that specifies whether the specified CommandBar is enabled. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Enabled

expression A variable that represents a CommandBar object.

Remarks

For command bars, setting this property to True causes the name of the command bar to appear in the list of available command bars.

For built-in controls, if you set the Enabled property to True, the application determines its state, but setting it to False will force it to be disabled.

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Height Property (Office)

 Copy code hover
[image]

CommandBar.Height Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the height of a CommandBar. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Height

expression A variable that represents a CommandBar object.

Return Value

Integer

Example

This example adds a custom control to the command bar named Custom. The example sets the height of the custom control to twice the height of the command bar and sets the control's width to 50 pixels. Notice how the command bar automatically resizes itself to accommodate the control.

VBA Copy code Copy code
Set myBar = CommandBars("Custom")
barHeight = myBar.Height
Set myControl = myBar.Controls _
    .Add(Type:=msoControlButton, _
    Id:= CommandBars("Standard").Controls("Save").Id, _
     Temporary:=True)
With myControl
    .Height = barHeight * 2
    .Width = 50
End With
myBar.Visible = True

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Index Property (Office)

 Copy code hover
[image]

CommandBar.Index Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a Long representing the index number for a CommandBar object in the collection. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Index

expression A variable that represents a CommandBar object.

Return Value

Long

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Left Property (Office)

 Copy code hover
[image]

CommandBar.Left Property (Office)
See also Send feedback

Published: June 15, 2012

Sets or gets the horizontal distance (in pixels) of the CommandBar from the left edge of the object relative to the screen. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Left

expression Required. A variable that represents a CommandBar object.

Example

This example moves the command bar named Custom from its docked position along the top of the window to the left edge of the window.

VBA Copy code Copy code
Set myBar = CommandBars("Custom")
With myBar
    .Position = 1
    .RowIndex = 2
    .Left = 0
End With

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Name Property (Office)

 Copy code hover
[image]

CommandBar.Name Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the name of the built-in CommandBar object. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Name

expression A variable that represents a CommandBar object.

Remarks

The local name of a built-in command bar is displayed in the title bar (when the command bar isn't docked) and in the list of available command bars — wherever that list is displayed in the container application. For a built-in command bar, the Name property returns the command bar's U.S. English name. Use the NameLocal property to return the localized name. If you change the value of the LocalName property for a custom command bar, the value of Name changes as well, and vice versa.

Example

This example searches the collection of command bars for the command bar named "Custom." If this command bar is found, the example makes it visible.

VBA Copy code Copy code
foundFlag =  False
For Each bar In CommandBars
    If bar.Name = "Custom" Then
        foundFlag = True
        bar.Visible = True
    End If
Next
If Not foundFlag Then
    MsgBox "'Custom' bar isn't in collection."
Else
    MsgBox "'Custom' bar is now visible."
End If

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.NameLocal Property (Office)

 Copy code hover
[image]

CommandBar.NameLocal Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the name of a built-in command bar as it's displayed in the language version of the container application, or returns or sets the name of a custom command bar. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .NameLocal

expression A variable that represents a CommandBar object.

Remarks

Note Note

If you attempt to set this property for a built-in command bar, an error occurs.

The local name of a built-in command bar is displayed in the title bar (when the command bar isn't docked) and in the list of available command bars, wherever that list is displayed in the container application.

If you change the value of the LocalName property for a custom command bar, the value of Name changes as well, and vice versa.

Example

This example displays the name and localized name of the first command bar in the container application.

Copy code Copy code
With CommandBars(1)
    MsgBox "The name of the command bar is " & .Name
    MsgBox "The localized name of the command bar is " & .NameLocal
End With

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Parent Property (Office)

 Copy code hover
[image]

CommandBar.Parent Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the Parent object for the CommandBar object. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Parent

expression A variable that represents a CommandBar object.

Return Value

Object

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Position Property (Office)

 Copy code hover
[image]

CommandBar.Position Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets a MsoBarPosition constant representing the position of a command bar. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Position

expression A variable that represents a CommandBar object.

Example

This example steps through the collection of command bars, docking the custom command bars at the bottom of the application window and docking the built-in command bars at the top of the window.

Copy code Copy code
For Each bar In CommandBars
    If bar.Visible = True Then
        If bar.BuiltIn Then
            bar.Position = msoBarTop
         Else
            bar.Position = msoBarBottom
        End If
    End If
Next

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Protection Property (Office)

 Copy code hover
[image]

CommandBar.Protection Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets a MsoBarProtection constant representing the way a command bar is protected from user customization. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Protection

expression A variable that represents a CommandBar object.

Remarks

Using the constant msoBarNoCustomize prevents users from accessing the Add or Remove Buttons menu (this menu enables users to customize a toolbar).

Example

This example steps through the collection of command bars to find the command bar named "Forms." If this command bar is found, it's docking state is protected and it's made visible.

Copy code Copy code
foundFlag =  False
For i = 1 To CommandBars.Count
    If CommandBars(i).Name = "Forms" Then
            CommandBars(i).Protection = msoBarNoChangeDock
            CommandBars(i).Visible = True
            foundFlag = True
    End If
Next
If Not foundFlag Then
    MsgBox "'Forms' command bar is not in the collection."
End If

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.RowIndex Property (Office)

 Copy code hover
[image]

CommandBar.RowIndex Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the docking order of a command bar in relation to other command bars in the same docking area. Can be an integer greater than zero, or either of the following MsoBarRow constants: msoBarRowFirst or msoBarRowLast. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .RowIndex

expression A variable that represents a CommandBar object.

Remarks

Several command bars can share the same row index, and command bars with lower numbers are docked first. If two or more command bars share the same row index, the command bar most recently assigned will be displayed first in its group.

Example

This example adjusts the position of the command bar named "Custom" by moving it to the left 110 pixels more than the default, and it makes this command bar the first to be docked by changing its row index to msoBarRowFirst.

Copy code Copy code
Set myBar = CommandBars("Custom")
With myBar
    .RowIndex = msoBarRowFirst
    .Left = 140
End With

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Top Property (Office)

 Copy code hover
[image]

CommandBar.Top Property (Office)
See also Send feedback

Published: June 15, 2012

Sets or gets the distance from the top edge of the specified command bar, to the top edge of the screen. For docked command bars, this property returns or sets the distance from the command bar to the top of the docking area. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Top

expression Required. A variable that represents a CommandBar object.

Example

This example positions the upper-left corner of the floating command bar named "Custom" 140 pixels from the left edge of the screen and 100 pixels from the top of the screen.

VBA Copy code Copy code
Set myBar = CommandBars("Custom")
myBar.Position = msoBarFloating
With myBar
    .Left = 140
    .Top = 100
End With

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Type Property (Office)

 Copy code hover
[image]

CommandBar.Type Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the type of command bar. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Type

expression Required. A variable that represents a CommandBar object.

Example

This example finds the first control on the command bar named "Custom." Using the Type property, the example determines whether the control is a button. If the control is a button, the example copies the face of the Copy button (on the Standard toolbar) and then pastes it onto the control.

VBA Copy code Copy code
Set oldCtrl = CommandBars("Custom").Controls(1)
If oldCtrl.Type = msoControlButton Then
    Set newCtrl = CommandBars.FindControl(Type:= _
        MsoControlButton, ID:= _
        CommandBars("Standard").Controls("Copy").ID)
    NewCtrl.CopyFace
    OldCtrl.PasteFace
End If

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Visible Property (Office)

 Copy code hover
[image]

CommandBar.Visible Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the Visible property of the command bar. True if the command bar is visible. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Visible

expression A variable that represents a CommandBar object.

Return Value

Boolean

Remarks

The Visible property for newly created custom command bars is False by default.

The Enabled property for a command bar must be set to True before the Visible property is set to True.

Example

This example steps through the collection of command bars to find the Forms command bar. If the Forms command bar is found, the example makes it visible and protects its docking state.

VBA Copy code Copy code
foundFlag = False
For Each cmdbar In CommandBars
    If cmdbar.Name = "Forms" Then
        cmdbar.Protection = msoBarNoChangeDock
        cmdbar.Visible = True
        foundFlag = True
    End If
Next
If Not foundFlag Then
    MsgBox "'Forms'command bar is not in the collection."
End If

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Width Property (Office)

 Copy code hover
[image]

CommandBar.Width Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the width (in pixels) of the specified command bar. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Width

expression A variable that represents a CommandBar object.

Return Value

Integer

Example

This example adds a custom control to the command bar named Custom. The example sets the height of the custom control to twice the height of the command bar and sets its width to 50 pixels. Notice how the command bar automatically resizes itself to accommodate the control.

VBA Copy code Copy code
Set myBar = CommandBars("Custom")
barHeight = myBar.Height
Set myControl = myBar.Controls _
    .Add(Type:=msoControlButton, _
    Id:= CommandBars("Standard").Controls("Save").Id, _
     Temporary:=True)
With myControl
    .Height = barHeight * 2
    .Width = 50
End With
myBar.Visible = True

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar Methods (Office)

 Copy code hover
[image]

CommandBar Methods (Office)
Send feedback

Published: June 15, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes the CommandBar object from the collection.
FindControl | Gets a CommandBarControl object that fits a specified criteria.
Reset | Resets a built-in command bar to its default configuration.
ShowPopup | Displays a command bar as a shortcut menu at the specified coordinates or at the current pointer coordinates.


CommandBar.Delete Method (Office)

 Copy code hover
[image]

CommandBar.Delete Method (Office)
See also Send feedback

Published: June 15, 2012

Deletes the CommandBar object from the collection.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Delete

expression Required. A variable that represents a CommandBar object.

Remarks

For the Scripts collection, using the Delete method removes all scripts from the specified Microsoft Word document, Microsoft Excel worksheet, or Microsoft PowerPoint slide. A script anchor is represented by a shape in the host application. Therefore, the Shape object associated with each script anchor of type msoScriptAnchor is deleted from the Shapes collection in Excel and PowerPoint and from the InlineShapes and Shapes collections in Word.

Example

This example deletes all custom command bars that are not visible.

VBA Copy code Copy code
foundFlag = False
delBars = 0
For Each bar In CommandBars
    If (bar.BuiltIn = False) And _
    (bar.Visible = False) Then
        bar.Delete
        foundFlag =
        delBars = delBars + 1
    End If
Next bar
If Not foundFlag Then
    MsgBox "No command bars have been deleted."
Else
    MsgBox delBars & " custom bar(s) deleted."
End If

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.FindControl Method (Office)

 Copy code hover
[image]

CommandBar.FindControl Method (Office)
See also Send feedback

Published: June 15, 2012

Gets a CommandBarControl object that fits a specified criteria.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .FindControl(Type, Id, Tag, Visible, Recursive)

expression A variable that represents a CommandBar object.

Parameters

Name | Required/Optional | Data Type | Description
Type | Optional | Variant | The type of control.
Id | Optional | Variant | The identifier of the control.
Tag | Optional | Variant | The tag value of the control.
Visible | Optional | Variant | True to include only visible command bar controls in the search. The default value is False. Visible command bars include all visible toolbars and any menus that are open at the time the FindControl method is executed.
Recursive | Optional | Variant | True to include the command bar and all of its pop-up subtoolbars in the search. This argument only applies to the CommandBar object. The default value is False.

Return Value

CommandBarControl

Remarks

If the CommandBars collection contains two or more controls that fit the search criteria, FindControl returns the first control that's found. If no control that fits the criteria is found, FindControl returns Nothing.

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.Reset Method (Office)

 Copy code hover
[image]

CommandBar.Reset Method (Office)
See also Send feedback

Published: June 15, 2012

Resets a built-in command bar to its default configuration.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Reset

expression A variable that represents a CommandBar object.

Remarks

Resetting a built-in control restores the actions originally intended for the control and resets each of the control's properties back to its original state. Resetting a built-in command bar removes custom controls and restores built-in controls.

Example

This example uses the value of User to adjust the command bars according to the user level. If User is "Level 1," the command bar named "Custom" is displayed. If User is any other value, the built-in Visual Basic command bar is reset to its default state and the command bar named "Custom" is disabled.

VBA Copy code Copy code
Set myBar = CommandBars("Custom")
If user = "Level 1" Then
    myBar.Visible =  True
Else
    CommandBars("Visual Basic").Reset
    myBar.Enabled = False
End If

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBar.ShowPopup Method (Office)

 Copy code hover
[image]

CommandBar.ShowPopup Method (Office)
See also Send feedback

Published: June 15, 2012

Displays a command bar as a shortcut menu at the specified coordinates or at the current pointer coordinates.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .ShowPopup(x, y)

expression A variable that represents a CommandBar object.

Parameters

Name | Required/Optional | Data Type | Description
x | Optional | Variant | The x-coordinate on which the location of the shortcut menu is based. If this argument is omitted, the current x-coordinate of the pointer is used.
y | Optional | Variant | The y-coordinate on which the location of the shortcut menu is based. If this argument is omitted, the current y-coordinate of the pointer is used.

Remarks

When menus are left-aligned, the shortcut menu displayed by the ShowPopup method has its upper left corner at (x, y + 1); when menus are right-aligned, the shortcut menu has its upper right corner at (x + 1, y + 1). You can use the Windows function GetSystemMetrics(SM_MENUDROPALIGNMENT) to check the system metric for dropdown menu alignment.

When the screen location of the (x, y) coordinates would cause all or part of the popup menu to be displayed beyond the edge of the visible screen, then the popup menu shifts to fit into the viewable area.

Example

This example creates a shortcut menu containing two controls. The ShowPopup method is used to make the shortcut menu visible.

Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarPopup, Temporary:=False)
With myBar
    .Controls.Add Type:=msoControlButton, Id:=3
    .Controls.Add Type:=msoControlComboBox
End With
myBar.ShowPopup
Note Note

Note Note

If the Position property of the command bar is not set to msoBarPopup, this method fails.

See also

Concepts

CommandBar Object

Other resources

CommandBar Object Members


CommandBarButton Object (Office)

 Copy code hover
[image]

CommandBarButton Object (Office)
See also Send feedback

Published: June 15, 2012

Represents a button control on a command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Example

Use Controls(index), where index is the index number of the control, to return a CommandBarButton object. Note that the Type property of the control must be msoControlButton. Assuming that the second control on the command bar named "Custom" is a button, the following example changes the style of that button.

Copy code Copy code
Set c = CommandBars("Custom").Controls(2)
With c
If .Type = msoControlButton Then
    If .Style = msoButtonIcon Then
        .Style = msoButtonIconAndCaption
    Else
        .Style = msoButtonIcon
    End If
End If
End With
Note Note

Note Note

You can also use the FindControl method to return a CommandBarButton object.

See also

Concepts

Object Model Reference

Other resources

CommandBarButton Object Members


CommandBarButton Members (Office)

 Copy code hover
[image]

CommandBarButton Members (Office)
Send feedback

Published: June 15, 2012

Represents a button control on a command bar.

Events

Name | Description
Click | Occurs when the user clicks a CommandBarButton object.

Methods

Name | Description
Copy | Copies a command bar button control to an existing command bar.
CopyFace | Copies the face of a command bar button control to the Clipboard.
Delete | Deletes the CommandBarButton object from its collection.
Execute | Runs the procedure or built-in command assigned to the specified CommandBarButton control.
Move | Moves the specified CommandBarButton control to an existing command bar.
PasteFace | Pastes the contents of the Clipboard onto a CommandBarButton.
Reset | Resets a built-in CommandBarButton control to its original function and face.
SetFocus | Moves the keyboard focus to the specified CommandBarButton control. If the button is disabled or isn't visible, this method will fail.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CommandBarButton object (you can use this property with an Automation object to return that object's container application). Read-only.
BeginGroup | Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.
BuiltIn | Is True if the specified command bar control is a control of the container application. Returns False if it's a custom control, or if it's a built-in control whose OnAction property has been set. Read-only.
BuiltInFace | Is True if the face of a command bar button control is its original built-in face. Read/write.
Caption | Gets or sets the caption text for a command bar control. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBarButton object was created. Read-only.
DescriptionText | Gets or sets the description for a command bar button control. Read/write.
Enabled | True if the specified CommandBar or CommandBarControl is enabled. Read/write .
FaceId | Gets or sets the Id number for the face of a CommandBarButton control. Read/write.
Height | Gets or sets the height of a command bar control. Read/write.
HelpContextId | Gets or sets the Help context Id number for the Help topic attached to the CommandBarButton control. Read/write.
HelpFile | Gets or sets the file name for the Help topic attached to the CommandBarButton control. Read/write.
HyperlinkType | Sets or gets a MsoCommandBarButtonHyperlinkType constant that represents the type of hyperlink associated with the specified command bar button. Read/write.
Id | Gets the ID for a built-in CommandBarButton control. Read-only.
Index | Gets a Long representing the index number for an CommandBarButton object in the collection. Read-only.
IsPriorityDropped | Gets True if the CommandBarButton control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.
Left | Set or gets the horizontal position of the specified CommandBarButton control (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.
Mask | Gets or sets an IPictureDisp object representing the mask image of a CommandBarButton object. The mask image determines what parts of the button image are transparent. Read/write.
OLEUsage | Gets or sets the OLE client and OLE server roles in which a CommandBarButton control will be used when two Microsoft Office applications are merged. Read/write.
OnAction | Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarButton control. Read/write.
Parameter | Gets or sets a string that an application can use to execute a command from a CommandBarButton control. Read/write.
Parent | Gets the Parent object for the CommandBarButton object. Read-only.
Picture | Gets or sets an IPictureDisp object representing the image of a CommandBarButton object. Read/write.
Priority | Gets or sets the priority of a CommandBarButton control. A control's priority determines whether the control can be dropped from a docked command bar if the command bar controls can't fit in a single row. Controls that can't fit in a single row drop off command bars from right to left. Read/write.
ShortcutText | Gets or sets the shortcut key text displayed next to a CommandBarButton control when the button appears on a menu, submenu, or shortcut menu. Read/write.
State | Gets or sets the appearance of a CommandBarButton control. Read/write.
Style | Gets or sets the way a CommandBarButton control is displayed. Read/write.
Tag | Gets or sets information about the CommandBarButton control, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.
TooltipText | Gets or sets the text displayed in a CommandBarButton's ScreenTip. Read/write.
Top | Gets the distance (in pixels) from the top edge of the specified CommandBarButton control to the top edge of the screen. Read-only.
Type | Gets the type of CommandBarButton control. Read-only.
Visible | Gets or sets the Visible property of the CommandBarButton control. True if the CommandBarButton is visible. Read/write.
Width | Gets or sets the width (in pixels) of the specified CommandBarButton control. Read/write.


CommandBarButton Properties (Office)

 Copy code hover
[image]

CommandBarButton Properties (Office)
Send feedback

Published: June 15, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CommandBarButton object (you can use this property with an Automation object to return that object's container application). Read-only.
BeginGroup | Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.
BuiltIn | Is True if the specified command bar control is a control of the container application. Returns False if it's a custom control, or if it's a built-in control whose OnAction property has been set. Read-only.
BuiltInFace | Is True if the face of a command bar button control is its original built-in face. Read/write.
Caption | Gets or sets the caption text for a command bar control. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBarButton object was created. Read-only.
DescriptionText | Gets or sets the description for a command bar button control. Read/write.
Enabled | True if the specified CommandBar or CommandBarControl is enabled. Read/write .
FaceId | Gets or sets the Id number for the face of a CommandBarButton control. Read/write.
Height | Gets or sets the height of a command bar control. Read/write.
HelpContextId | Gets or sets the Help context Id number for the Help topic attached to the CommandBarButton control. Read/write.
HelpFile | Gets or sets the file name for the Help topic attached to the CommandBarButton control. Read/write.
HyperlinkType | Sets or gets a MsoCommandBarButtonHyperlinkType constant that represents the type of hyperlink associated with the specified command bar button. Read/write.
Id | Gets the ID for a built-in CommandBarButton control. Read-only.
Index | Gets a Long representing the index number for an CommandBarButton object in the collection. Read-only.
IsPriorityDropped | Gets True if the CommandBarButton control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.
Left | Set or gets the horizontal position of the specified CommandBarButton control (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.
Mask | Gets or sets an IPictureDisp object representing the mask image of a CommandBarButton object. The mask image determines what parts of the button image are transparent. Read/write.
OLEUsage | Gets or sets the OLE client and OLE server roles in which a CommandBarButton control will be used when two Microsoft Office applications are merged. Read/write.
OnAction | Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarButton control. Read/write.
Parameter | Gets or sets a string that an application can use to execute a command from a CommandBarButton control. Read/write.
Parent | Gets the Parent object for the CommandBarButton object. Read-only.
Picture | Gets or sets an IPictureDisp object representing the image of a CommandBarButton object. Read/write.
Priority | Gets or sets the priority of a CommandBarButton control. A control's priority determines whether the control can be dropped from a docked command bar if the command bar controls can't fit in a single row. Controls that can't fit in a single row drop off command bars from right to left. Read/write.
ShortcutText | Gets or sets the shortcut key text displayed next to a CommandBarButton control when the button appears on a menu, submenu, or shortcut menu. Read/write.
State | Gets or sets the appearance of a CommandBarButton control. Read/write.
Style | Gets or sets the way a CommandBarButton control is displayed. Read/write.
Tag | Gets or sets information about the CommandBarButton control, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.
TooltipText | Gets or sets the text displayed in a CommandBarButton's ScreenTip. Read/write.
Top | Gets the distance (in pixels) from the top edge of the specified CommandBarButton control to the top edge of the screen. Read-only.
Type | Gets the type of CommandBarButton control. Read-only.
Visible | Gets or sets the Visible property of the CommandBarButton control. True if the CommandBarButton is visible. Read/write.
Width | Gets or sets the width (in pixels) of the specified CommandBarButton control. Read/write.


CommandBarButton.Application Property (Office)

 Copy code hover
[image]

CommandBarButton.Application Property (Office)
See also Send feedback

Published: June 15, 2012

Gets an Application object that represents the container application for the CommandBarButton object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Application

expression A variable that represents a CommandBarButton object.

Return Value

Object

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.BeginGroup Property (Office)

 Copy code hover
[image]

CommandBarButton.BeginGroup Property (Office)
See also Send feedback

Published: June 15, 2012

Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .BeginGroup

expression A variable that represents a CommandBarButton object.

Return Value

Boolean

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.BuiltIn Property (Office)

 Copy code hover
[image]

CommandBarButton.BuiltIn Property (Office)
See also Send feedback

Published: June 15, 2012

Is True if the specified command bar control is a control of the container application. Returns False if it's a custom control, or if it's a built-in control whose OnAction property has been set. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .BuiltIn

expression A variable that represents a CommandBarButton object.

Return Value

Boolean

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.BuiltInFace Property (Office)

 Copy code hover
[image]

CommandBarButton.BuiltInFace Property (Office)
See also Send feedback

Published: June 15, 2012

Is True if the face of a command bar button control is its original built-in face. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .BuiltInFace

expression A variable that represents a CommandBarButton object.

Remarks

This property can only be set to True, which will reset the face to the built-in face. Read/write Boolean.

Example

This example determines whether the face of the first control on the command bar named "Custom" is its built-in button face. If it is, the example copies the button face to the Clipboard.

Copy code Copy code
Set myControl = CommandBars("My Custom Bar").Controls(1)
With myControl
    If .BuiltInFace = True Then .CopyFace
End With

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Caption Property (Office)

 Copy code hover
[image]

CommandBarButton.Caption Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the caption text for a command bar control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Caption

expression A variable that represents a CommandBarButton object.

Return Value

String

Example

This example adds a command bar control with a spelling checker button face to a custom command bar, and then it sets the caption to "Spelling checker."

VBA Copy code Copy code
Set myBar = CommandBars.Add(Name:="Custom", _
Position:=msoBarTop, Temporary:=True)
myBar.Visible = True
Set myControl = myBar.Controls _
.Add(Type:=msoControlButton, Id:=2)
With myControl
    .DescriptionText = "Starts the spelling checker"
    .Caption = "Spelling checker"
End With
Note Note

Note Note

A control's caption is also displayed as its default ScreenTip.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Creator Property (Office)

 Copy code hover
[image]

CommandBarButton.Creator Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a 32-bit integer that indicates the application in which the CommandBarButton object was created. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Creator

expression A variable that represents a CommandBarButton object.

Return Value

Long

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.DescriptionText Property (Office)

 Copy code hover
[image]

CommandBarButton.DescriptionText Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the description for a command bar button control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .DescriptionText

expression A variable that represents a CommandBarButton object.

Return Value

String

Remarks

The description is not displayed to the user, but it can be useful for documenting the behavior of the control for other developers.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Enabled Property (Office)

 Copy code hover
[image]

CommandBarButton.Enabled Property (Office)
See also Send feedback

Published: June 15, 2012

True if the specified CommandBar or CommandBarControl is enabled. Read/write .

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Enabled

expression A variable that represents a CommandBarButton object.

Return Value

Boolean

Remarks

For command bars, setting this property to True causes the name of the command bar to appear in the list of available command bars.

For built-in controls, if you set the Enabled property to True, the application determines its state, but setting it to False will force it to be disabled.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.FaceId Property (Office)

 Copy code hover
[image]

CommandBarButton.FaceId Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the Id number for the face of a CommandBarButton control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .FaceId

expression A variable that represents a CommandBarButton object.

Remarks

The FaceId property dictates the look, not the function, of a command bar button. The Id property of the CommandBarControl object determines the function of the button.

The value of the FaceId property for a command bar button with a custom face is 0 (zero).

Example

This example adds a command bar button to a custom command bar. Clicking this button is equivalent to clicking the Open command on the File menu because the ID number is 23, yet the button has the same button face as the built-in Charting button.

Copy code Copy code
Set newBar = CommandBars.Add(Name:="Custom2", _
     Position:=msoBarTop, Temporary:=True)
newBar.Visible = True
Set con = newBar.Controls.Add(Type:=msoControlButton, Id:=23)
con.FaceId = 17

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Height Property (Office)

 Copy code hover
[image]

CommandBarButton.Height Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the height of a command bar control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Height

expression A variable that represents a CommandBarButton object.

Return Value

Integer

Example

This example adds a custom control to the command bar named Custom. The example sets the height of the custom control to twice the height of the command bar and sets the control's width to 50 pixels. Notice how the command bar automatically resizes itself to accommodate the control.

VBA Copy code Copy code
Set myBar = CommandBars("Custom")
barHeight = myBar.Height
Set myControl = myBar.Controls _
    .Add(Type:=msoControlButton, _
    Id:= CommandBars("Standard").Controls("Save").Id, _
     Temporary:=True)
With myControl
    .Height = barHeight * 2
    .Width = 50
End With
myBar.Visible = True

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.HelpContextId Property (Office)

 Copy code hover
[image]

CommandBarButton.HelpContextId Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the Help context Id number for the Help topic attached to the CommandBarButton control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .HelpContextId

expression A variable that represents a CommandBarButton object.

Return Value

Integer

Remarks

To use this property, you must also set the HelpFile property. Help topics respond to Shift+F1.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.HelpFile Property (Office)

 Copy code hover
[image]

CommandBarButton.HelpFile Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the file name for the Help topic attached to the CommandBarButton control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .HelpFile

expression A variable that represents a CommandBarButton object.

Return Value

String

Remarks

To use this property, you must also set the HelpContextID property. Help topics respond to the user pressing SHIFT+F1.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.HyperlinkType Property (Office)

 Copy code hover
[image]

CommandBarButton.HyperlinkType Property (Office)
See also Send feedback

Published: June 15, 2012

Sets or gets a MsoCommandBarButtonHyperlinkType constant that represents the type of hyperlink associated with the specified command bar button. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .HyperlinkType

expression A variable that represents a CommandBarButton object.

Example

This example checks the HyperlinkType property for the specified command bar button on the command bar named "Custom.". If HyperlinkType is set to msoCommandBarButtonHyperlinkNone, the example sets the property to msoCommandBarButtonHyperlinkOpen and sets the URL to www.microsoft.com.

Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
Set myButton = myBar.Controls.Add(Type:=msoControlButton)
With myButton
    .FaceId = 277
    .HyperlinkType = msoCommandBarButtonHyperlinkNone
End With
If myButton.HyperlinkType > _
    msoCommandBarButtonHyperlinkOpen Then
    myButton.HyperlinkType = _
        msoCommandBarButtonHyperlinkOpen
    myButton.TooltipText = "www.microsoft.com"
End If

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Id Property (Office)

 Copy code hover
[image]

CommandBarButton.Id Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the ID for a built-in CommandBarButton control. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Id

expression Required. A variable that represents a CommandBarButton object.

Remarks

A control's ID determines the built-in action for that control. The value of the Id property for all custom controls is 1.

Example

This example changes the button face of the first control on the command bar named "Custom2" if the button's ID value is less than 25.

VBA Copy code Copy code
Set ctrl = CommandBars("Custom").Controls(1)
With ctrl
    If .Id < 25 Then
        .FaceId = 17
        .Tag = "Changed control"
    End If
End With

The following example changes the caption of every control on the toolbar named "Standard" to the current value of the Id property for that control.

VBA Copy code Copy code
For Each ctl In CommandBars("Standard").Controls
    ctl.Caption = CStr(ctl.Id)
Next ctl

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Index Property (Office)

 Copy code hover
[image]

CommandBarButton.Index Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a Long representing the index number for an CommandBarButton object in the collection. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Index

expression A variable that represents a CommandBarButton object.

Return Value

Integer

Remarks

The position of the first command bar control is 1. Separators are not counted in the CommandBarControls collection.

Example

This example searches the command bar named "Custom2" for a control with an Id value of 23. If such a control is found and the index number of the control is greater than 5, the control will be positioned as the first control on the command bar.

VBA Copy code Copy code
Set myBar = CommandBars("Custom2")
Set ctrl1 = myBar.FindControl(Id:=23)
If ctrl1.Index > 5 Then
    ctrl1.Move before:=1
End If

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.IsPriorityDropped Property (Office)

 Copy code hover
[image]

CommandBarButton.IsPriorityDropped Property (Office)
See also Send feedback

Published: June 15, 2012

Gets True if the CommandBarButton control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .IsPriorityDropped

expression A variable that represents a CommandBarButton object.

Return Value

Boolean

Remarks

A control with Visible set to True, will not be immediately visible on a personalized menu or toolbar if IsPriorityDropped is True.

To determine when to set IsPriorityDropped to True for a specific menu item, Microsoft Office maintains a total count of the number of times the menu item was used and a record of the number of different application sessions in which the user has used another menu item in the same menu as this menu item, without using the specific menu item. When this value reaches certain threshold values, the count is decremented. When the count reaches zero, IsPriorityDropped is set to True. Programmers cannot set the session value, the threshold value, or the IsPriorityDropped property. Programmers can, however, use the AdaptiveMenus property to disable adaptive menus for specific menus in an application.

To determine when to set IsPriorityDropped to True for a specific toolbar control, Office maintains a list of the order in which all the controls on that toolbar were last executed. A toolbar will always show as many controls as it has space to show, in the order of most recently used to least recently used. Controls with Priority set to 1 will always be shown and the toolbar will wrap rows, if necessary, to show these controls. Programmers can use the Priority property to ensure that specific toolbar controls are always shown, or to reposition toolbars so that they have enough space to display all of their controls.

You can use the following table to predict the number of sessions for which a menu item on a personalized menu will remain visible before the menu item's IsPriorityDropped property is set to True.

Number of uses of the command bar control | Number of sessions of the application
0, 1 | 3
2 | 6
3 | 9
4, 5 | 12
6- 8 | 17
9-13 | 23
14-24 | 29
25 or more | 31

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Left Property (Office)

 Copy code hover
[image]

CommandBarButton.Left Property (Office)
See also Send feedback

Published: June 15, 2012

Set or gets the horizontal position of the specified CommandBarButton control (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Left

expression Required. A variable that represents a CommandBarButton object.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Mask Property (Office)

 Copy code hover
[image]

CommandBarButton.Mask Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets an IPictureDisp object representing the mask image of a CommandBarButton object. The mask image determines what parts of the button image are transparent. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Mask

expression A variable that represents a CommandBarButton object.

Remarks

When you create an image that you plan on using as a mask image, all of the areas that you want to be transparent should be white, and all of the areas that you want to show should be black.

Always set the mask after you have set the picture for a CommandBarButton object.

Example

The following example sets the image and mask of the first CommandBarButton that the code returns. To make this work, create a mask image and a button image and sustitute the paths in the sample with the paths to your images.

Copy code Copy code
Sub ChangeButtonImage()
    Dim picPicture As IPictureDisp
    Dim picMask As IPictureDisp

    Set picPicture = stdole.StdFunctions.LoadPicture( _
        "c:\images\picture.bmp")
    Set picMask = stdole.StdFunctions.LoadPicture( _
        "c:\images\mask.bmp")

    'Reference the first button on the first command bar
    'using a With...End With block.
    With Application.CommandBars.FindControl(msoControlButton)
        'Change the button image.
        .Picture = picPicture

        'Use the second image to define the area of the
        'button that should be transparent.
        .Mask = picMask
    End With
End Sub

The following example gets the image and mask of the first CommandBarButton that the code returns and outputs each of them to a file. To make this work, specify a path for the output files.

Copy code Copy code
Sub GetButtonImageAndMask()
    Dim picPicture As IPictureDisp
    Dim picMask As IPictureDisp

    With Application.CommandBars.FindControl(msoControlButton)
        'Get the button image and mask of this CommandBarButton object
        Set picPicture = .Picture
        Set picMask = .Mask
    End With

    'Save the button image and mask in a folder.
    stdole.SavePicture picPicture, "c:\image.bmp"
    stdole.SavePicture picMask, "c:\mask.bmp"
End Sub

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.OLEUsage Property (Office)

 Copy code hover
[image]

CommandBarButton.OLEUsage Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the OLE client and OLE server roles in which a CommandBarButton control will be used when two Microsoft Office applications are merged. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .OLEUsage

expression A variable that represents a CommandBarButton object.

Return Value

MsoControlOLEUsage

Remarks

This property is intended to allow you to specify how individual add-in applications' command bar controls will be represented in one Office application when it is merged with another Office application. If both the client and server implement command bars, the command bar controls are embedded in the client control by control. Custom controls marked as client-only (or neither client nor server) are dropped from the server, and controls marked as server-only (or neither server nor client) are dropped from the client. The remaining controls are merged.

If one of the merging applications isn't an Office application, normal OLE menu merging is used, which is controlled by the OLEMenuGroup property.

Example

This example adds a new button to the command bar named "Tools", and sets its OLEUsage property.

VBA Copy code Copy code
Set myControl = CommandBars("Tools").Controls _
    .Add(Type:=msoControlButton,Temporary:=True)
myControl.OLEUsage = msoControlOLEUsageNeither

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.OnAction Property (Office)

 Copy code hover
[image]

CommandBarButton.OnAction Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarButton control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .OnAction

expression A variable that represents a CommandBarButton object.

Return Value

String

Remarks

The container application determines whether the value is a valid macro name.

Example

This example adds a command bar control to the command bar named "Custom". The COM add in named "FinanceAddIn" will run each time the control is clicked.

VBA Copy code Copy code
Set myBar = CommandBars("Custom")
Set myControl = myBar.Controls _
    .Add(Type:=msocontrolButton)
With myControl
    .FaceId = 2
    .OnAction = "!<FinanceAddIn>"
End With
myBar.Visible = True

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Parameter Property (Office)

 Copy code hover
[image]

CommandBarButton.Parameter Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets a string that an application can use to execute a command from a CommandBarButton control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Parameter

expression A variable that represents a CommandBarButton object.

Return Value

String

Remarks

If the specified parameter is set for a built-in control, the application can modify its default behavior if it can parse and use the new value. If the parameter is set for custom controls, it can be used to send information to Visual Basic procedures, or it can be used to hold information about the control (similar to a second Tag property value).

Example

This example assigns a new parameter to a control and sets the focus to the new button.

VBA Copy code Copy code
Set myControl = CommandBars("Custom").Controls(4)
With myControl
    .Copy , 1
    .Parameter = "2"
    .SetFocus
End With

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Parent Property (Office)

 Copy code hover
[image]

CommandBarButton.Parent Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the Parent object for the CommandBarButton object. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Parent

expression A variable that represents a CommandBarButton object.

Return Value

CommandBar

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Picture Property (Office)

 Copy code hover
[image]

CommandBarButton.Picture Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets an IPictureDisp object representing the image of a CommandBarButton object. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Picture

expression A variable that represents a CommandBarButton object.

Remarks

When you change the image on a button, you will also want to use the Mask property to set a mask image. The mask image determines which parts of the button image are transparent. Always set the mask after you have set the picture for a CommandBarButton object.

Note Note

The images for the View Microsoft Application and Insert Item buttons on the Standard toolbar in the Visual Basic Editor cannot be changed.

Example

The following example sets the image and mask of the first CommandBarButton that the code returns. To make this work, create a mask image and a button image and substitute the paths in the sample with the paths to your images.

Copy code Copy code
Sub ChangeButtonImage()
    Dim picPicture As IPictureDisp
    Dim picMask As IPictureDisp

    Set picPicture = stdole.StdFunctions.LoadPicture( _
        "c:\images\picture.bmp")
    Set picMask = stdole.StdFunctions.LoadPicture( _
        "c:\images\mask.bmp")

    'Reference the first button on the first command bar
    'using a With...End With block.
    With Application.CommandBars.FindControl(msoControlButton)
        'Change the button image.
        .Picture = picPicture

        'Use the second image to define the area of the
        'button that should be transparent.
        .Mask = picMask
    End With
End Sub

The following example gets the image and mask of the first CommandBarButton that the code returns and outputs each of them to a file. To make this work, specify a path for the output files.

Copy code Copy code
Sub GetButtonImageAndMask()
    Dim picPicture As IPictureDisp
    Dim picMask As IPictureDisp

    With Application.CommandBars.FindControl(msoControlButton)
        'Get the button image and mask of this CommandBarButton object.
        Set picPicture = .Picture
        Set picMask = .Mask
    End With

    'Save the button image and mask in a folder.
    stdole.SavePicture picPicture, "c:\image.bmp"
    stdole.SavePicture picMask, "c:\mask.bmp"
End Sub

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Priority Property (Office)

 Copy code hover
[image]

CommandBarButton.Priority Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the priority of a CommandBarButton control. A control's priority determines whether the control can be dropped from a docked command bar if the command bar controls can't fit in a single row. Controls that can't fit in a single row drop off command bars from right to left. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Priority

expression A variable that represents a CommandBarButton object.

Remarks

Valid priority numbers are 0 (zero) through 7 and the default value is 3. A priority of 1 means that the control cannot be dropped from a toolbar. Other priority values are ignored.

The Priority property is not used by command bar controls that are menu items.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.ShortcutText Property (Office)

 Copy code hover
[image]

CommandBarButton.ShortcutText Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the shortcut key text displayed next to a CommandBarButton control when the button appears on a menu, submenu, or shortcut menu. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .ShortcutText

expression A variable that represents a CommandBarButton object.

Remarks

You can set this property only for command bar buttons that contain an OnAction macro.

Example

This example displays the shortcut text for the Open command (File menu) on the Microsoft Excel Worksheet menu bar in a message box.

Copy code Copy code
MsgBox (CommandBars("Worksheet Menu Bar"). _
    Controls("File").Controls("New...).ShortcutText)

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.State Property (Office)

 Copy code hover
[image]

CommandBarButton.State Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the appearance of a CommandBarButton control. Read/write.

Syntax

expression .State

expression Required. A variable that represents a CommandBarButton object.

Remarks

The State property of built-in command bar buttons is read-only. The value of the Type property is available as a value in the MsoButtonState enumeration.

Example

This example creates a command bar named "Custom" and adds two buttons to it. The example then sets the button on the left to msoButtonUp and sets the button on the right to msoButtonDown.

VBA Copy code Copy code
 Dim myBar As Office.CommandBar
 Dim imgSource As Office.CommandBarButton
 Dim myControl1 As Office.CommandBarButton
 Dim myControl2 As Office.CommandBarButton
 ' Add new command bar.
 Set myBar = CommandBars.Add(Name:="Custom", Position:=msoBarTop, Temporary:=True)
 ' Add 2 buttons to new command bar.
 With myBar
 .Controls.Add Type:=msoControlButton
 .Controls.Add Type:=msoControlButton
 .Visible = True
 End With
 ' Paste Bold button face and set State of first button.
 Set myControl1 = myBar.Controls(1)
 Set imgSource = CommandBars.FindControl(msoControlButton, 113)
 imgSource.CopyFace
 With myControl1
 .PasteFace
 .State = msoButtonUp
 End With
 ' Paste italic button face and set State of second button.
 Set myControl2 = myBar.Controls(2)
 Set imgSource = CommandBars.FindControl(msoControlButton, 114)
 imgSource.CopyFace
 With myControl2
 .PasteFace
 .State = msoButtonDown
 End With

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Style Property (Office)

 Copy code hover
[image]

CommandBarButton.Style Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the way a CommandBarButton control is displayed. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Style

expression A variable that represents a CommandBarButton object.

Remarks

The value of the Style property is available as a value in the MsoButtonStyle enumeration.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Tag Property (Office)

 Copy code hover
[image]

CommandBarButton.Tag Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets information about the CommandBarButton control, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Tag

expression A variable that represents a CommandBarButton object.

Return Value

String

Example

To avoid duplicate calls of the same class when tiggered with events, define the Tag property unique to the events. The following example demonstrates this concept with two modules.

VBA Copy code Copy code
Public WithEvents oBtn As CommandBarButton

Private Sub oBtn_click(ByVal ctrl As Office.CommandBarButton, CancelDefault As Boolean)
    MsgBox "Clicked " & ctrl.Caption

End Sub

Dim oBtns As New Collection

Sub Use_Tag()

    Dim oEvt As CBtnEvent
    Set oBtns = Nothing

    For i = 1 To 5
        Set oEvt = New CBtnEvent
        Set oEvt.oBtn = Application.CommandBars("Worksheet Menu Bar").Controls.Add(msoControlButton)
        With oEvt.oBtn
            .Caption = "Btn" & i
            .Style = msoButtonCaption
            .Tag = "Hello" & i
        End With
        oBtns.Add oEvt
    Next

End Sub

This example sets the tag for the button on the custom command bar to "Spelling Button" and displays the tag in a message box.

Copy code Copy code
CommandBars("Custom").Controls(1).Tag = "Spelling Button"
MsgBox (CommandBars("Custom").Controls(1).Tag)

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.TooltipText Property (Office)

 Copy code hover
[image]

CommandBarButton.TooltipText Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the text displayed in a CommandBarButton's ScreenTip. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .TooltipText

expression A variable that represents a CommandBarButton object.

Return Value

String

Remarks

By default, the value of the Caption property is used as the ScreenTip.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Top Property (Office)

 Copy code hover
[image]

CommandBarButton.Top Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the distance (in pixels) from the top edge of the specified CommandBarButton control to the top edge of the screen. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Top

expression Required. A variable that represents a CommandBarButton object.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Type Property (Office)

 Copy code hover
[image]

CommandBarButton.Type Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the type of CommandBarButton control. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Type

expression Required. A variable that represents a CommandBarButton object.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Visible Property (Office)

 Copy code hover
[image]

CommandBarButton.Visible Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the Visible property of the CommandBarButton control. True if the CommandBarButton is visible. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Visible

expression A variable that represents a CommandBarButton object.

Return Value

Boolean

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Width Property (Office)

 Copy code hover
[image]

CommandBarButton.Width Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the width (in pixels) of the specified CommandBarButton control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Width

expression A variable that represents a CommandBarButton object.

Return Value

Integer

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton Methods (Office)

 Copy code hover
[image]

CommandBarButton Methods (Office)
Send feedback

Published: June 15, 2012

This object has the following methods:

Methods

Name | Description
Copy | Copies a command bar button control to an existing command bar.
CopyFace | Copies the face of a command bar button control to the Clipboard.
Delete | Deletes the CommandBarButton object from its collection.
Execute | Runs the procedure or built-in command assigned to the specified CommandBarButton control.
Move | Moves the specified CommandBarButton control to an existing command bar.
PasteFace | Pastes the contents of the Clipboard onto a CommandBarButton.
Reset | Resets a built-in CommandBarButton control to its original function and face.
SetFocus | Moves the keyboard focus to the specified CommandBarButton control. If the button is disabled or isn't visible, this method will fail.


CommandBarButton.Copy Method (Office)

 Copy code hover
[image]

CommandBarButton.Copy Method (Office)
See also Send feedback

Published: June 15, 2012

Copies a command bar button control to an existing command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Copy(Bar, Before)

expression A variable that represents a CommandBarButton object.

Parameters

Name | Required/Optional | Data Type | Description
Bar | Optional | Variant | A CommandBar object that represents the destination command bar. If this argument is omitted, the control is copied to the command bar where the control already exists.
Before | Optional | Variant | A number that indicates the position for the new control on the command bar. The new control will be inserted before the control at this position. If this argument is omitted, the control is copied to the end of the command bar.

Return Value

CommandBarControl

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.CopyFace Method (Office)

 Copy code hover
[image]

CommandBarButton.CopyFace Method (Office)
See also Send feedback

Published: June 15, 2012

Copies the face of a command bar button control to the Clipboard.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .CopyFace

expression A variable that represents a CommandBarButton object.

Remarks

Use the PasteFace method to paste the contents of the Clipboard onto a button face.

Example

This example finds the built-in Open button, copies the button face to the Clipboard, and then pastes the face onto the Spelling and Grammar button.

Copy code Copy code
Set myControl = CommandBars.FindControl(Type:=msoControlButton, Id:=23)
myControl.CopyFace
Set myControl = CommandBars.FindControl(Type:=msoControlButton, ID:=2)
myControl.PasteFace

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Delete Method (Office)

 Copy code hover
[image]

CommandBarButton.Delete Method (Office)
See also Send feedback

Published: June 15, 2012

Deletes the CommandBarButton object from its collection.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Delete(Temporary)

expression Required. A variable that represents a CommandBarButton object.

Parameters

Name | Required/Optional | Data Type | Description
Temporary | Optional | Variant | True to delete the control for the current session. The application will display the control again in the next session.

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Execute Method (Office)

 Copy code hover
[image]

CommandBarButton.Execute Method (Office)
See also Send feedback

Published: June 15, 2012

Runs the procedure or built-in command assigned to the specified CommandBarButton control.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Execute

expression Required. A variable that represents a CommandBarButton object.

Example

This Microsoft Excel example creates a command bar and then adds a built-in command bar button control to it. The button executes the Excel AutoSum function. This example uses the Execute method to total the selected range of cells when the command bar appears.

VBA Copy code Copy code
Dim cbrCustBar As CommandBar
Dim ctlAutoSum As CommandBarButton
Set cbrCustBar = CommandBars.Add("Custom")
Set ctlAutoSum = cbrCustBar.Controls _
    .Add(msoControlButton, CommandBars("Standard") _
    .Controls("AutoSum").Id)
cbrCustBar.Visible = True
ctlAutoSum.Execute

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Move Method (Office)

 Copy code hover
[image]

CommandBarButton.Move Method (Office)
See also Send feedback

Published: June 15, 2012

Moves the specified CommandBarButton control to an existing command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Move(Bar, Before)

expression Required. A variable that represents a CommandBarButton object.

Parameters

Name | Required/Optional | Data Type | Description
Bar | Optional | Variant | A Command object that represents the destination command bar for the control. If this argument is omitted, the control is moved to the end of the command bar where the control currently resides.
Before | Optional | Variant | A number that indicates the position for the control. The control is inserted before the control currently occupying this position. If this argument is omitted, the control is inserted on the same command bar.

Example

This example moves the first combo box control on the command bar named Custom to the position before the seventh control on that command bar. The example sets the tag to "Selection box" and assigns the control a low priority so that it will likely be dropped from the command bar if all the controls don't fit in one row.

VBA Copy code Copy code
Set allcontrols = CommandBars("Custom").Controls
For Each ctrl In allControls
    If ctrl.Type = msoControlComboBox Then
        With ctrl
            .Move Before:=7
             .Tag = "Selection box"
             .Priority = 5
         End With
         Exit For
    End If
Next

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.PasteFace Method (Office)

 Copy code hover
[image]

CommandBarButton.PasteFace Method (Office)
See also Send feedback

Published: June 15, 2012

Pastes the contents of the Clipboard onto a CommandBarButton.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .PasteFace

expression A variable that represents a CommandBarButton object.

Example

This example finds the built-in FileOpen button and pastes the face from the Spelling and Grammar button onto it from the Clipboard.

Copy code Copy code
Set myControl = CommandBars.FindControl(Type:=msoControlButton, Id:=2)
myControl.CopyFace
Set myControl = CommandBars.FindControl(Type:=msoControlButton, Id:=23)
myControl.PasteFace

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.Reset Method (Office)

 Copy code hover
[image]

CommandBarButton.Reset Method (Office)
See also Send feedback

Published: June 15, 2012

Resets a built-in CommandBarButton control to its original function and face.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Reset

expression A variable that represents a CommandBarButton object.

Remarks

Resetting a built-in control restores the actions originally intended for the control and resets each of the control's properties back to its original state.

Example

This example customizes a command bar button. First, the button properties are reset to their default state. Then various button properties are set.

Copy code Copy code
Dim cbButton As CommandBarButton
Set cbButton = CommandBars("Custom").Controls(2)
cbButton.Reset
With cbButton
    .BuiltInFace = True
    .Caption = "Compute Total"
    .DescriptionText = "This button computes the total of all purchases."
    .Enabled = True
    .TooltipText = "Click to compute total amount for all items in your cart."
End With

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton.SetFocus Method (Office)

 Copy code hover
[image]

CommandBarButton.SetFocus Method (Office)
See also Send feedback

Published: June 15, 2012

Moves the keyboard focus to the specified CommandBarButton control. If the button is disabled or isn't visible, this method will fail.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .SetFocus

expression A variable that represents a CommandBarButton object.

Remarks

The focus on the control is subtle. After you use this method, you will notice a three dimensional highlight on the control. Pressing the arrow keys will navigate in the toolbars, as if you had arrived at the control by pressing only keyboard controls.

Example

This example creates a command bar named "Custom" and adds a ComboBox control and a Button control to it. The example then uses the SetFocus method to set the focus to the ComboBox control.

VBA Copy code Copy code
Set focusBar = CommandBars.Add(Name:="Custom")
With CommandBars("Custom")
    .Visible = True
    .Position = msoBarTop
End With

Set testComboBox = CommandBars("Custom").Controls _
    .Add(Type:=msoControlComboBox, ID:=1)
With testComboBox
    .AddItem "First Item", 1
    .AddItem "Second Item", 2
End With
Set testButton = CommandBars("Custom").Controls _
    .Add(Type:=msoControlButton)
testButton.FaceId = 17
' Set the focus to the combo box.
testComboBox.SetFocus

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarButton Events (Office)

 Copy code hover
[image]

CommandBarButton Events (Office)
Send feedback

Published: June 15, 2012

This object has the following events:

Events

Name | Description
Click | Occurs when the user clicks a CommandBarButton object.


CommandBarButton.Click Event (Office)

 Copy code hover
[image]

CommandBarButton.Click Event (Office)
See also Send feedback

Published: June 15, 2012

Occurs when the user clicks a CommandBarButton object.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Click(Ctrl, CancelDefault)

expression A variable that represents a CommandBarButton object.

Parameters

Name | Required/Optional | Data Type | Description
Ctrl | Required | CommandBarButton | Represents a CommandBar button
CancelDefault | Required | Boolean | Is False if the default behavior associated with the CommandBarButton controls occurs, unless it's canceled by another process or add-in.

Remarks

The Click event is recognized by the CommandBarButton object. To return the Click event for a particular CommandBarButton control, use the WithEvents keyword to declare a variable, and then set the variable to the control.

Example

The following example creates a command bar button on the File menu of the host application that enables the user to save a workbook as a comma-separated value file. (This example works in all applications, but the context of saving as CSV is applicable to Microsoft Excel.)

Copy code Copy code
Private HostApp As Object

Sub createAndSynch()
    Dim iIndex As Integer
    Dim iCount As Integer
    Dim fBtnExists As Boolean

    Dim obCmdBtn As Object
    Dim btnSaveAsCSVHandler as new Class1

    Set HostApp = Application

    Dim barHelp As Office.CommandBar
    Set barHelp = Application.CommandBars("File")
    fBtnExists = False
    iCount = barHelp.Controls.Count
    For iIndex = 1 To iCount
        If barHelp.Controls(iIndex).Caption = "Save As CSV (Comma Delimited)" Then fBtnExists = True

    Next
    Dim btnSaveAsCSV As Office.CommandBarButton
    If fBtnExists Then
        Set btnSaveAsCSV = barHelp.Controls("Save As CSV (Comma Delimited)")
    Else
        Set btnSaveAsCSV = barHelp.Controls.Add(msoControlButton)
        btnSaveAsCSV.Caption = "Save As CSV (Comma Delimited)"
    End If

    btnSaveAsCSV.Tag = "btn1"
    btnSaveAsCSVHandler.SyncButton btnSaveAsCSV
End Sub

See also

Concepts

CommandBarButton Object

Other resources

CommandBarButton Object Members


CommandBarComboBox Object (Office)

 Copy code hover
[image]

CommandBarComboBox Object (Office)
See also Send feedback

Published: June 15, 2012

Represents a combo box control on a command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Remarks

Use Controls(index), where index is the index number of the control, to return a CommandBarComboBox object. Note that the Type property of the control must be msoControlEdit, msoControlDropdown, msoControlComboBox, msoControlButtonDropdown, msoControlSplitDropdown, msoControlOCXDropdown, msoControlGraphicCombo, or msoControlGraphicDropdown.

Example

The following example adds two items to the second control on the command bar named Custom, and then it adjusts the size of the control.

Copy code Copy code
Set combo = CommandBars("Custom").Controls(2)
With combo
    .AddItem "First Item", 1
    .AddItem "Second Item", 2
    .DropDownLines = 3
    .DropDownWidth = 75
    .ListIndex = 0
End With

You can also use the FindControl method to return a CommandBarComboBox object. The following example searches all command bars for a visible CommandBarComboBox object whose tag is "sheet assignments."

Copy code Copy code
Set myControl = CommandBars.FindControl _
(Type:=msoControlComboBox, Tag:="sheet assignments", Visible:=True)

See also

Concepts

Object Model Reference

Other resources

CommandBarComboBox Object Members


CommandBarComboBox Members (Office)

 Copy code hover
[image]

CommandBarComboBox Members (Office)
Send feedback

Published: June 15, 2012

Represents a combo box control on a command bar.

Events

Name | Description
Change | Occurs when the end user changes the selection in a CommandBar combo box.

Methods

Name | Description
AddItem | Adds a list item to the specified command bar combo box control. The combo box control must be a custom control and must be a drop-down list box or a combo box.
Clear | Removes all list items from a command bar combo box control (a drop-down list box or a combo box).
Copy | Copies a command bar combo box control to an existing command bar.
Delete | Deletes CommandBarCombo control object from its collection.
Execute | Runs the procedure or built-in command assigned to the specified CommandBarComboBox control.
Move | Moves the specified control to an existing command bar.
RemoveItem | Removes an item from a CommandBarComboBox control.
Reset | Resets a built-in command bar to its default configuration, or resets a built-in CommandBarComboBox control to its original function and face.
SetFocus | Moves the keyboard focus to the specified CommandBarComboBox control. If the control is disabled or isn't visible, this method will fail.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CommandBarComboBox object (you can use this property with an Automation object to return that object's container application). Read-only.
BeginGroup | Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.
BuiltIn | Gets True if the specified command bar control is a built-in control of the container application. Returns False if it's a custom control, or if it's a built-in control whose OnAction property has been set. Read-only.
Caption | Gets or sets the caption text for a command bar control. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBarComboBox object was created. Read-only.
DescriptionText | Gets or sets the description for a command bar combo box control. Read/write.
DropDownLines | Gets or sets the number of lines in a command bar combo box control. The combo box control must be a custom control and it must be a drop-down list box or a combo box. Read/write.
DropDownWidth | Gets or sets the width (in pixels) of the list for the specified command bar combo box control. Read/write.
Enabled | Gets or sets a Boolean value that specifies whether the CommandBarComboBox is enabled. Read/write.
Height | Gets or sets the height of a CommandBarComboBox control. Read/write.
HelpContextId | Gets or sets the Help context Id number for the Help topic attached to the CommandBarComboBox control. Read/write.
HelpFile | Gets or sets the file name for the Help topic attached to the CommandBarComboBox control. Read/write.
Id | Gets the ID for a built-in CommandBarComboBox control. Read-only.
Index | Gets a Long representing the index number for a CommandBarComboBox object in the collection. Read-only.
IsPriorityDropped | Gets True if the control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.
Left | Gets the horizontal position of the CommandBarComboBox control (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.
List | Gets or sets an item in the CommandBarComboBox control. Read/write.
ListCount | Gets the number of list items in a CommandBarComboBox control. Read-only.
ListHeaderCount | Gets or sets the number of list items in a CommandBarComboBox control that appears above the separator line. Read/write.
ListIndex | Gets or sets the index number of the selected item in the list portion of the CommandBarComboBox control. If nothing is selected in the list, this property returns zero. Read/write.
OLEUsage | Gets or sets the OLE client and OLE server roles in which a CommandBarComboBox control will be used when two Microsoft Office applications are merged. Read/write.
OnAction | Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarComboBox control. Read/write.
Parameter | Gets or sets a string that an application can use to execute a command from a CommandBarComboBox control. Read/write.
Parent | Gets the Parent object for the CommandBarComboBox object. Read-only.
Priority | Gets or sets the priority of a CommandBarComboBox control. A control's priority determines whether the control can be dropped from a docked command bar if the command bar controls can't fit in a single row. Read/write.
Style | Gets or sets the way a CommandBarComboBox control is displayed. Can be either of the following MsoComboStyle constants: msoComboLabel or msoComboNormal. Read/write.
Tag | Gets or sets information about the CommandBarComboBox control, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.
Text | Gets or sets the text in the display or edit portion of the CommandBarComboBox control. Read/write.
TooltipText | Gets or sets the text displayed in a CommandBarComboBox's ScreenTip. Read/write.
Top | Gets the distance (in pixels) from the top edge of the specified CommandBarComboBox control to the top edge of the screen. Read-only.
Type | Gets the type of CommandBarComboBox control. Read-only.
Visible | Gets or sets the Visible property for the CommandBarComboBox control. True if the CommandBarControl is visible. Read/write.
Width | Gets or sets the width (in pixels) of the specified CommandBarComboBox control. Read/write.


CommandBarComboBox Properties (Office)

 Copy code hover
[image]

CommandBarComboBox Properties (Office)
Send feedback

Published: June 15, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CommandBarComboBox object (you can use this property with an Automation object to return that object's container application). Read-only.
BeginGroup | Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.
BuiltIn | Gets True if the specified command bar control is a built-in control of the container application. Returns False if it's a custom control, or if it's a built-in control whose OnAction property has been set. Read-only.
Caption | Gets or sets the caption text for a command bar control. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBarComboBox object was created. Read-only.
DescriptionText | Gets or sets the description for a command bar combo box control. Read/write.
DropDownLines | Gets or sets the number of lines in a command bar combo box control. The combo box control must be a custom control and it must be a drop-down list box or a combo box. Read/write.
DropDownWidth | Gets or sets the width (in pixels) of the list for the specified command bar combo box control. Read/write.
Enabled | Gets or sets a Boolean value that specifies whether the CommandBarComboBox is enabled. Read/write.
Height | Gets or sets the height of a CommandBarComboBox control. Read/write.
HelpContextId | Gets or sets the Help context Id number for the Help topic attached to the CommandBarComboBox control. Read/write.
HelpFile | Gets or sets the file name for the Help topic attached to the CommandBarComboBox control. Read/write.
Id | Gets the ID for a built-in CommandBarComboBox control. Read-only.
Index | Gets a Long representing the index number for a CommandBarComboBox object in the collection. Read-only.
IsPriorityDropped | Gets True if the control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.
Left | Gets the horizontal position of the CommandBarComboBox control (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.
List | Gets or sets an item in the CommandBarComboBox control. Read/write.
ListCount | Gets the number of list items in a CommandBarComboBox control. Read-only.
ListHeaderCount | Gets or sets the number of list items in a CommandBarComboBox control that appears above the separator line. Read/write.
ListIndex | Gets or sets the index number of the selected item in the list portion of the CommandBarComboBox control. If nothing is selected in the list, this property returns zero. Read/write.
OLEUsage | Gets or sets the OLE client and OLE server roles in which a CommandBarComboBox control will be used when two Microsoft Office applications are merged. Read/write.
OnAction | Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarComboBox control. Read/write.
Parameter | Gets or sets a string that an application can use to execute a command from a CommandBarComboBox control. Read/write.
Parent | Gets the Parent object for the CommandBarComboBox object. Read-only.
Priority | Gets or sets the priority of a CommandBarComboBox control. A control's priority determines whether the control can be dropped from a docked command bar if the command bar controls can't fit in a single row. Read/write.
Style | Gets or sets the way a CommandBarComboBox control is displayed. Can be either of the following MsoComboStyle constants: msoComboLabel or msoComboNormal. Read/write.
Tag | Gets or sets information about the CommandBarComboBox control, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.
Text | Gets or sets the text in the display or edit portion of the CommandBarComboBox control. Read/write.
TooltipText | Gets or sets the text displayed in a CommandBarComboBox's ScreenTip. Read/write.
Top | Gets the distance (in pixels) from the top edge of the specified CommandBarComboBox control to the top edge of the screen. Read-only.
Type | Gets the type of CommandBarComboBox control. Read-only.
Visible | Gets or sets the Visible property for the CommandBarComboBox control. True if the CommandBarControl is visible. Read/write.
Width | Gets or sets the width (in pixels) of the specified CommandBarComboBox control. Read/write.


CommandBarComboBox.Application Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Application Property (Office)
See also Send feedback

Published: June 15, 2012

Gets an Application object that represents the container application for the CommandBarComboBox object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Application

expression A variable that represents a CommandBarComboBox object.

Return Value

Object

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.BeginGroup Property (Office)

 Copy code hover
[image]

CommandBarComboBox.BeginGroup Property (Office)
See also Send feedback

Published: June 15, 2012

Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .BeginGroup

expression A variable that represents a CommandBarComboBox object.

Return Value

Boolean

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.BuiltIn Property (Office)

 Copy code hover
[image]

CommandBarComboBox.BuiltIn Property (Office)
See also Send feedback

Published: June 15, 2012

Gets True if the specified command bar control is a built-in control of the container application. Returns False if it's a custom control, or if it's a built-in control whose OnAction property has been set. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .BuiltIn

expression A variable that represents a CommandBarComboBox object.

Return Value

Boolean

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Caption Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Caption Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the caption text for a command bar control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Caption

expression A variable that represents a CommandBarComboBox object.

Return Value

String

Note Note

Note Note

A control's caption is also displayed as its default ScreenTip.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Creator Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Creator Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a 32-bit integer that indicates the application in which the CommandBarComboBox object was created. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Creator

expression A variable that represents a CommandBarComboBox object.

Return Value

Long

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.DescriptionText Property (Office)

 Copy code hover
[image]

CommandBarComboBox.DescriptionText Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the description for a command bar combo box control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .DescriptionText

expression A variable that represents a CommandBarComboBox object.

Return Value

String

Remarks

The description is not displayed to the user, but it can be useful for documenting the behavior of the control for other developers.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.DropDownLines Property (Office)

 Copy code hover
[image]

CommandBarComboBox.DropDownLines Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the number of lines in a command bar combo box control. The combo box control must be a custom control and it must be a drop-down list box or a combo box. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .DropDownLines

expression A variable that represents a CommandBarComboBox object.

Remarks

Note Note

An error occurs if you attempt to set this property for a combo box control that's an edit box or a built-in combo box control.

If this property is set to 0 (zero), the number of lines in the control is based on the number of items in the list.

Example

This example adds a combo box control containing two items to the command bar named "Custom". The example also sets the number of line items, the width of the combo box, and an empty default for the combo box.

Copy code Copy code
Set myBar = CommandBars("Custom")
Set myControl = myBar.Controls.Add(Type:=msoControlComboBox, Id:=1)
With myControl
    .AddItem Text:="First Item", Index:=1
    .AddItem "Second Item", 2
    .DropDownLines = 3
    .DropDownWidth = 75
    .ListHeaderCount = 0
End With

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.DropDownWidth Property (Office)

 Copy code hover
[image]

CommandBarComboBox.DropDownWidth Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the width (in pixels) of the list for the specified command bar combo box control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .DropDownWidth

expression A variable that represents a CommandBarComboBox object.

Remarks

Note Note

An error occurs if you attempt to set this property for a built-in control.

If this property is set to -1, the width of the list is based on the length of the longest item in the combo box list. If this property is set to 0, the width of the list is based on the width of the control.

Example

This example adds a combo box control containing two items to the command bar named "Custom". The example also sets the number of line items, the width of the combo box, and an empty default for the combo box.

Copy code Copy code
Set myBar = CommandBars("Custom")
Set myControl = myBar.Controls.Add(Type:=msoControlComboBox, Id:=1)
With myControl
    .AddItem "First Item", 1
    .AddItem "Second Item", 2
    .DropDownLines = 3
    .DropDownWidth = 75
    .ListHeaderCount = 0
End With

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Enabled Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Enabled Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets a Boolean value that specifies whether the CommandBarComboBox is enabled. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Enabled

expression A variable that represents a CommandBarComboBox object.

Remarks

For command bars, setting this property to True causes the name of the command bar to appear in the list of available command bars.

For built-in controls, if you set the Enabled property to True, the application determines its state, but setting it to False will force it to be disabled.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Height Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Height Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the height of a CommandBarComboBox control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Height

expression A variable that represents a CommandBarComboBox object.

Return Value

Integer

Example

This example adds a custom control to the command bar named Custom. The example sets the height of the custom control to twice the height of the command bar and sets the control's width to 50 pixels. Notice how the command bar automatically resizes itself to accommodate the control.

VBA Copy code Copy code
Set myBar = CommandBars("Custom")
barHeight = myBar.Height
Set myControl = myBar.Controls _
    .Add(Type:=msoControlButton, _
    Id:= CommandBars("Standard").Controls("Save").Id, _
     Temporary:=True)
With myControl
    .Height = barHeight * 2
    .Width = 50
End With
myBar.Visible = True

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.HelpContextId Property (Office)

 Copy code hover
[image]

CommandBarComboBox.HelpContextId Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the Help context Id number for the Help topic attached to the CommandBarComboBox control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .HelpContextId

expression A variable that represents a CommandBarComboBox object.

Return Value

Integer

Remarks

To use this property, you must also set the HelpFile property. Help topics respond to Shift+F1.

Example

This example adds a custom command bar with a combo box that tracks stock data. The example also specifies the Help topic to be displayed for the combo box when the user presses SHIFT+F1.

VBA Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
With myBar
    .Controls.Add Type:=msoControlComboBox, ID:=1
    .Visible = True
End With
With CommandBars("Custom").Controls(1)
    .AddItem "Get Stock Quote", 1
    .AddItem "View Chart", 2
    .AddItem "View Fundamentals", 3
    .AddItem "View News", 4
    .Caption = "Stock Data"
    .DescriptionText = "View Data For Stock"
    .HelpFile = "C:\corphelp\custom.hlp"
    .HelpContextID = 47
End With

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.HelpFile Property (Office)

 Copy code hover
[image]

CommandBarComboBox.HelpFile Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the file name for the Help topic attached to the CommandBarComboBox control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .HelpFile

expression A variable that represents a CommandBarComboBox object.

Return Value

String

Remarks

To use this property, you must also set the HelpContextID property. Help topics respond to the user pressing SHIFT+F1.

Example

This example adds a custom command bar with a combo box that tracks stock data. The example also specifies the Help topic to be displayed for the combo box when the user presses SHIFT+F1.

VBA Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
With myBar
    .Controls.Add Type:=msoControlComboBox, ID:=1
    .Visible = True
End With
With CommandBars("Custom").Controls(1)
    .AddItem "Get Stock Quote", 1
    .AddItem "View Chart", 2
    .AddItem "View Fundamentals", 3
    .AddItem "View News", 4
    .Caption = "Stock Data"
    .DescriptionText = "View Data For Stock"
    .HelpFile = "C:\corphelp\custom.hlp"
    .HelpContextID = 47
End With

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Id Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Id Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the ID for a built-in CommandBarComboBox control. Read-only.

Syntax

expression .Id

expression Required. A variable that represents a CommandBarComboBox object.

Remarks

A control's ID determines the built-in action for that control. The value of the Id property for all custom controls is 1.

Example

This example changes the button face of the first control on the command bar named "Custom2" if the button's ID value is less than 25.

VBA Copy code Copy code
Set ctrl = CommandBars("Custom").Controls(1)
With ctrl
 If .Id < 25 Then
 .FaceId = 17
 .Tag = "Changed control"
 End If
End With

The following example changes the caption of every control on the toolbar named "Standard" to the current value of the Id property for that control.

VBA Copy code Copy code
For Each ctl In CommandBars("Standard").Controls
 ctl.Caption = CStr(ctl.Id)
Next ctl

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Index Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Index Property (Office)
See also Send feedback

Published: June 15, 2012

Gets a Long representing the index number for a CommandBarComboBox object in the collection. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Index

expression A variable that represents a CommandBarComboBox object.

Return Value

Long

Remarks

The position of the first command bar control is 1. Separators are not counted in the CommandBarControls collection.

Example

This example searches the command bar named "Custom2" for a control with an Id value of 23. If such a control is found and the index number of the control is greater than 5, the control will be positioned as the first control on the command bar.

VBA Copy code Copy code
Set myBar = CommandBars("Custom2")
Set ctrl1 = myBar.FindControl(Id:=23)
If ctrl1.Index > 5 Then
    ctrl1.Move before:=1
End If

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.IsPriorityDropped Property (Office)

 Copy code hover
[image]

CommandBarComboBox.IsPriorityDropped Property (Office)
See also Send feedback

Published: June 15, 2012

Gets True if the control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .IsPriorityDropped

expression A variable that represents a CommandBarComboBox object.

Return Value

Boolean

Remarks

A control with Visible set to True, will not be immediately visible on a personalized menu or toolbar if IsPriorityDropped is True.

To determine when to set IsPriorityDropped to True for a specific menu item, Microsoft Office maintains a total count of the number of times the menu item was used and a record of the number of different application sessions in which the user has used another menu item in the same menu as this menu item, without using the specific menu item. When this value reaches certain threshold values, the count is decremented. When the count reaches zero, IsPriorityDropped is set to True. Programmers cannot set the session value, the threshold value, or the IsPriorityDropped property. Programmers can, however, use the AdaptiveMenus property to disable adaptive menus for specific menus in an application.

To determine when to set IsPriorityDropped to True for a specific toolbar control, Office maintains a list of the order in which all the controls on that toolbar were last executed. A toolbar will always show as many controls as it has space to show, in the order of most recently used to least recently used. Controls with Priority set to 1 will always be shown and the toolbar will wrap rows, if necessary, to show these controls. Programmers can use the Priority property to ensure that specific toolbar controls are always shown, or to reposition toolbars so that they have enough space to display all of their controls.

You can use the following table to predict the number of sessions for which a menu item on a personalized menu will remain visible before the menu item's IsPriorityDropped property is set to True.

Number of uses of the command bar control | Number of sessions of the application
0, 1 | 3
2 | 6
3 | 9
4, 5 | 12
6- 8 | 17
9-13 | 23
14-24 | 29
25 or more | 31

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Left Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Left Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the horizontal position of the CommandBarComboBox control (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Left

expression Required. A variable that represents a CommandBarComboBox object.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.List Property (Office)

 Copy code hover
[image]

CommandBarComboBox.List Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets an item in the CommandBarComboBox control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .List(Index)

expression A variable that represents a CommandBarComboBox object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Integer | The list item to be set.

Remarks

Note Note

This property is read-only for built-in combo box controls.

Example

This example checks the fourth list item in the combo box control whose caption is "Stock Data" on the command bar named "Custom." If the item isn't "View News," the example displays a message advising the user that the combo box may be damaged and asks the user to reinstall the application.

Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
With myBar
    .Controls.Add Type:=msoControlComboBox, ID:=1
    .Visible = True
End With
With CommandBars("Custom").Controls(1)
    .AddItem "Get Stock Quote", 1
    .AddItem "View Chart", 2
    .AddItem "View Fundamentals", 3
    .AddItem "View News", 4
    .Caption = "Stock Data"
    .DescriptionText = "View Data For Stock"
End With
If CommandBars("Custom").Controls(1).List(4) _
     > "View News" Then
MsgBox ("Stock Data appears to be damaged." & _
     " Please reinstall application.")
End If

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.ListCount Property (Office)

 Copy code hover
[image]

CommandBarComboBox.ListCount Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the number of list items in a CommandBarComboBox control. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .ListCount

expression A variable that represents a CommandBarComboBox object.

Example

This example checks the number of items in the combo box on the command bar named "Custom." If there aren't three items in the list that the procedure produces, the example displays a message advising the user that the combo box may be damaged and asks the user to reinstall the application.

Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
With myBar
    .Controls.Add Type:=msoControlComboBox, ID:=1
    .Visible = True
End With
With CommandBars("Custom").Controls(1)
    .AddItem "Get Stock Quote", 1
    .AddItem "View Chart", 2
    .AddItem "View Fundamentals", 3
    .Caption = "Stock Data"
    .DescriptionText = "View Data For Stock"
End With
If CommandBars("Custom").Controls(1).ListCount _
     > 4 Then
MsgBox ("ComboBox appears to be damaged." & _
     " Please reinstall.")
End If

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.ListHeaderCount Property (Office)

 Copy code hover
[image]

CommandBarComboBox.ListHeaderCount Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the number of list items in a CommandBarComboBox control that appears above the separator line. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .ListHeaderCount

expression A variable that represents a CommandBarComboBox object.

Remarks

Note Note

This property is read-only for built-in combo box controls.

A ListHeaderCount property value of - 1 indicates that there's no separator line in the combo box control.

Example

This example adds a combo box control to the command bar named "Custom" and then adds two items to the combo box. The example uses the ListHeaderCount property to display a separator line between First Item and Second Item in the combo box. The example also sets the number of line items, the width of the combo box, and an empty default for the combo box.

Copy code Copy code
Set myBar = CommandBars("Custom")
Set myControl = myBar.Controls.Add(Type:=msoControlComboBox)
With myControl
    .AddItem Text:="First Item", Index:=1
    .AddItem Text:="Second Item", Index:=2
    .DropDownLines = 3
    .DropDownWidth = 75
    .ListHeaderCount = 1
End With

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.ListIndex Property (Office)

 Copy code hover
[image]

CommandBarComboBox.ListIndex Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the index number of the selected item in the list portion of the CommandBarComboBox control. If nothing is selected in the list, this property returns zero. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .ListIndex

expression A variable that represents a CommandBarComboBox object.

Remarks

Note Note

This property fails when applied to controls other than list controls.

Setting the ListIndex property causes the specified control to select the given item and execute the appropriate action in the application.

Example

This example uses the ListIndex property to determine the correct subroutine to run, based on the selection in the combo box on the command bar named "My Custom Bar." Because the procedure uses ListIndex, the text in the combo box can be anything.

Copy code Copy code
Sub processSelection()
Dim userChoice As Long
userChoice = CommandBars("My Custom Bar").Controls(1).ListIndex
    Select Case userChoice
        Case 1
            chartcourse
        Case 2
            displaygraph
        Case Else
            MsgBox ("Invalid choice. Please choose again.")
    End Select
End Sub

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.OLEUsage Property (Office)

 Copy code hover
[image]

CommandBarComboBox.OLEUsage Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the OLE client and OLE server roles in which a CommandBarComboBox control will be used when two Microsoft Office applications are merged. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .OLEUsage

expression A variable that represents a CommandBarComboBox object.

Return Value

MsoControlOLEUsage

Remarks

This property is intended to allow you to specify how individual add-in applications' command bar controls will be represented in one Office application when it is merged with another Office application. If both the client and server implement command bars, the command bar controls are embedded in the client control by control. Custom controls marked as client-only (or neither client nor server) are dropped from the server, and controls marked as server-only (or neither server nor client) are dropped from the client. The remaining controls are merged.

If one of the merging applications isn't an Office application, normal OLE menu merging is used, which is controlled by the OLEMenuGroup property.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.OnAction Property (Office)

 Copy code hover
[image]

CommandBarComboBox.OnAction Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarComboBox control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .OnAction

expression A variable that represents a CommandBarComboBox object.

Return Value

String

Remarks

The container application determines whether the value is a valid macro name.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Parameter Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Parameter Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets a string that an application can use to execute a command from a CommandBarComboBox control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Parameter

expression A variable that represents a CommandBarComboBox object.

Return Value

String

Remarks

If the specified parameter is set for a built-in control, the application can modify its default behavior if it can parse and use the new value. If the parameter is set for custom controls, it can be used to send information to Visual Basic procedures, or it can be used to hold information about the control (similar to a second Tag property value).

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Parent Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Parent Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the Parent object for the CommandBarComboBox object. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Parent

expression A variable that represents a CommandBarComboBox object.

Return Value

CommandBar

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Priority Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Priority Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the priority of a CommandBarComboBox control. A control's priority determines whether the control can be dropped from a docked command bar if the command bar controls can't fit in a single row. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Priority

expression A variable that represents a CommandBarComboBox object.

Remarks

Valid priority numbers are 0 (zero) through 7 and the default value is 3. A priority of 1 means that the control cannot be dropped from a toolbar. Other priority values are ignored.

The Priority property is not used by command bar controls that are menu items.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Style Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Style Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the way a CommandBarComboBox control is displayed. Can be either of the following MsoComboStyle constants: msoComboLabel or msoComboNormal. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Style

expression A variable that represents a CommandBarComboBox object.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Tag Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Tag Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets information about the CommandBarComboBox control, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Tag

expression A variable that represents a CommandBarComboBox object.

Return Value

String

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Text Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Text Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the text in the display or edit portion of the CommandBarComboBox control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Text

expression A variable that represents a CommandBarComboBox object.

Return Value

String

Example

This example creates a new command bar named "Custom" and adds to it a combo box that contains four list items. The example then uses the Text property to set Item 3 as the default list item.

VBA Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
With myBar
    .Controls.Add Type:=msoControlComboBox, ID:=1
    .Visible = True
End With
Set testComboBox = CommandBars("Custom").Controls(1)
With testComboBox
    .AddItem "Item 1", 1
    .AddItem "Item 2", 2
    .AddItem "Item 3", 3
    .AddItem "Item 4", 4
    .Text = "Item 3"
End With

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.TooltipText Property (Office)

 Copy code hover
[image]

CommandBarComboBox.TooltipText Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the text displayed in a CommandBarComboBox's ScreenTip. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .TooltipText

expression A variable that represents a CommandBarComboBox object.

Return Value

String

Remarks

By default, the value of the Caption property is used as the ScreenTip.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Top Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Top Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the distance (in pixels) from the top edge of the specified CommandBarComboBox control to the top edge of the screen. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Top

expression Required. A variable that represents a CommandBarComboBox object.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Type Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Type Property (Office)
See also Send feedback

Published: June 15, 2012

Gets the type of CommandBarComboBox control. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Type

expression Required. A variable that represents a CommandBarComboBox object.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Visible Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Visible Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the Visible property for the CommandBarComboBox control. True if the CommandBarControl is visible. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Visible

expression A variable that represents a CommandBarComboBox object.

Return Value

Boolean

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Width Property (Office)

 Copy code hover
[image]

CommandBarComboBox.Width Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the width (in pixels) of the specified CommandBarComboBox control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Width

expression A variable that represents a CommandBarComboBox object.

Return Value

Integer

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox Methods (Office)

 Copy code hover
[image]

CommandBarComboBox Methods (Office)
Send feedback

Published: June 15, 2012

This object has the following methods:

Methods

Name | Description
AddItem | Adds a list item to the specified command bar combo box control. The combo box control must be a custom control and must be a drop-down list box or a combo box.
Clear | Removes all list items from a command bar combo box control (a drop-down list box or a combo box).
Copy | Copies a command bar combo box control to an existing command bar.
Delete | Deletes CommandBarCombo control object from its collection.
Execute | Runs the procedure or built-in command assigned to the specified CommandBarComboBox control.
Move | Moves the specified control to an existing command bar.
RemoveItem | Removes an item from a CommandBarComboBox control.
Reset | Resets a built-in command bar to its default configuration, or resets a built-in CommandBarComboBox control to its original function and face.
SetFocus | Moves the keyboard focus to the specified CommandBarComboBox control. If the control is disabled or isn't visible, this method will fail.


CommandBarComboBox.AddItem Method (Office)

 Copy code hover
[image]

CommandBarComboBox.AddItem Method (Office)
See also Send feedback

Published: June 15, 2012

Adds a list item to the specified command bar combo box control. The combo box control must be a custom control and must be a drop-down list box or a combo box.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .AddItem(Text, Index)

expression A variable that represents a CommandBarComboBox object.

Parameters

Name | Required/Optional | Data Type | Description
Text | Required | String | The text added to the control.
Index | Optional | Variant | The position of the item in the list. If this argument is omitted, the item is added to the end of the list.

Example

This example adds a combo box control to a command bar. Two items are added to the control, and the number of line items and the width of the combo box are set.

Copy code Copy code
Set myBar = CommandBars("Custom")
Set myControl = myBar.Controls.Add(Type:=msoControlComboBox, Id:=1)
With myControl
    .AddItem "First Item", 1
    .AddItem "Second Item", 2
    .DropDownLines = 3
    .DropDownWidth = 75
    .ListHeaderCount = 0
End With
Note Note

Note Note

This method will fail if it's applied to an edit box or a built-in combo box control.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Clear Method (Office)

 Copy code hover
[image]

CommandBarComboBox.Clear Method (Office)
See also Send feedback

Published: June 15, 2012

Removes all list items from a command bar combo box control (a drop-down list box or a combo box).

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Clear

expression An expression that returns a CommandBarComboBox object.

Remarks

Note Note

This method fails if it is applied to a built-in command bar control (a control that comes with Microsoft Office).

Example

This example checks the number of items in the combo box control on a command bar named Custom Bar. If there are fewer than three items in the list in the combo box, the example clears the list, adds a new first item to the list, and then displays this new item as the default for the combo box control.

VBA Copy code Copy code
Set myBar = CommandBars("Custom Bar")
Set myControl = myBar.Controls _
    Type:=msoControlComboBox)
With myControl
    .AddItem "First Item", 1
    .AddItem "Second Item", 2
End With
If myControl.ListCount < 3 Then
    myControl.Clear
    myControl.AddItem Text:="New Item", Index:=1
End If

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Copy Method (Office)

 Copy code hover
[image]

CommandBarComboBox.Copy Method (Office)
See also Send feedback

Published: June 15, 2012

Copies a command bar combo box control to an existing command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Copy(Bar, Before)

expression A variable that represents a CommandBarComboBox object.

Parameters

Name | Required/Optional | Data Type | Description
Bar | Optional | Variant | A CommandBar object that represents the destination command bar. If this argument is omitted, the control is copied to the command bar where the control already exists.
Before | Optional | Variant | A number that indicates the position for the new control on the command bar. The new control will be inserted before the control at this position. If this argument is omitted, the control is copied to the end of the command bar.

Return Value

CommandBarControl

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Delete Method (Office)

 Copy code hover
[image]

CommandBarComboBox.Delete Method (Office)
See also Send feedback

Published: June 15, 2012

Deletes CommandBarCombo control object from its collection.

Syntax

expression .Delete(Temporary)

expression Required. A variable that represents a CommandBarComboBox object.

Parameters

Name | Required/Optional | Data Type | Description
Temporary | Optional | Variant | True to delete the control for the current session. The application will display the control again in the next session.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Execute Method (Office)

 Copy code hover
[image]

CommandBarComboBox.Execute Method (Office)
See also Send feedback

Published: June 15, 2012

Runs the procedure or built-in command assigned to the specified CommandBarComboBox control.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Execute

expression Required. A variable that represents a CommandBarComboBox object.

Example

This Microsoft Excel example creates a command bar and then adds a built-in command bar button control to it. The button executes the Excel AutoSum function. This example uses the Execute method to total the selected range of cells when the command bar appears.

VBA Copy code Copy code
Dim cbrCustBar As CommandBar
Dim ctlAutoSum As CommandBarButton
Set cbrCustBar = CommandBars.Add("Custom")
Set ctlAutoSum = cbrCustBar.Controls _
    .Add(msoControlButton, CommandBars("Standard") _
    .Controls("AutoSum").Id)
cbrCustBar.Visible = True
ctlAutoSum.Execute

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Move Method (Office)

 Copy code hover
[image]

CommandBarComboBox.Move Method (Office)
See also Send feedback

Published: June 15, 2012

Moves the specified control to an existing command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Move(Bar, Before)

expression Required. A variable that represents a CommandBarComboBox object.

Parameters

Name | Required/Optional | Data Type | Description
Bar | Optional | Variant | A Command object that represents the destination command bar for the control. If this argument is omitted, the control is moved to the end of the command bar where the control currently resides.
Before | Optional | Variant | A number that indicates the position for the control. The control is inserted before the control currently occupying this position. If this argument is omitted, the control is inserted on the same command bar.

Example

This example moves the first combo box control on the command bar named Custom to the position before the seventh control on that command bar. The example sets the tag to "Selection box" and assigns the control a low priority so that it will likely be dropped from the command bar if all the controls don't fit in one row.

VBA Copy code Copy code
Set allcontrols = CommandBars("Custom").Controls
For Each ctrl In allControls
    If ctrl.Type = msoControlComboBox Then
        With ctrl
            .Move Before:=7
             .Tag = "Selection box"
             .Priority = 5
         End With
         Exit For
    End If
Next

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.RemoveItem Method (Office)

 Copy code hover
[image]

CommandBarComboBox.RemoveItem Method (Office)
See also Send feedback

Published: June 15, 2012

Removes an item from a CommandBarComboBox control.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .RemoveItem(Index)

expression A variable that represents a CommandBarComboBox object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Integer | The item to be removed from the list.

Example

This example determines whether there are more than three items in the specified combo box. If there are more than three items, the example removes the second item, alters the style, and sets a new value. It also sets the Tag property of the parent object (the CommandBarControl object) to show that the list has changed.

Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
With myBar
    .Controls.Add Type:=msoControlComboBox, ID:=1
    .Visible = True
End With
With CommandBars("Custom").Controls(1)
    .AddItem "Get Stock Quote", 1
    .AddItem "View Chart", 2
    .AddItem "View Fundamentals", 3
    .AddItem "View News", 4
    .Caption = "Stock Data"
    .DescriptionText = "View Data For Stock"
End With
Set myControl = myBar.Controls(1)
With myControl
    If .ListCount > 3 Then
        .RemoveItem 2
        .Style = msoComboNormal
        .Text = "New Default"
         Set ctrl = .Parent
    End If
End With
Note Note

Note Note

The property fails when applied to controls other than list controls.

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.Reset Method (Office)

 Copy code hover
[image]

CommandBarComboBox.Reset Method (Office)
See also Send feedback

Published: June 15, 2012

Resets a built-in command bar to its default configuration, or resets a built-in CommandBarComboBox control to its original function and face.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Reset

expression A variable that represents a CommandBarComboBox object.

Remarks

Resetting a built-in control restores the actions originally intended for the control and resets each of the control's properties back to its original state. Resetting a built-in command bar removes custom controls and restores built-in controls.

Example

This example customizes a command bar combo box. First, the combo box is reset to its default state. Then two line items are added to the combo box and various properties are set.

Copy code Copy code
Set combo = CommandBars("Custom").Controls(2)
combo.Reset
With combo
    .AddItem "First Item", 1
    .AddItem "Second Item", 2
    .DropDownLines = 3
    .DropDownWidth = 75
    .ListIndex = 0
End With

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox.SetFocus Method (Office)

 Copy code hover
[image]

CommandBarComboBox.SetFocus Method (Office)
See also Send feedback

Published: June 15, 2012

Moves the keyboard focus to the specified CommandBarComboBox control. If the control is disabled or isn't visible, this method will fail.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .SetFocus

expression A variable that represents a CommandBarComboBox object.

Example

This example creates a command bar named "Custom" and adds a ComboBox control and a Button control to it. The example then uses the SetFocus method to set the focus to the ComboBox control.

VBA Copy code Copy code
Set focusBar = CommandBars.Add(Name:="Custom")
With CommandBars("Custom")
    .Visible = True
    .Position = msoBarTop
End With

Set testComboBox = CommandBars("Custom").Controls _
    .Add(Type:=msoControlComboBox, ID:=1)
With testComboBox
    .AddItem "First Item", 1
    .AddItem "Second Item", 2
End With
Set testButton = CommandBars("Custom").Controls _
    .Add(Type:=msoControlButton)
testButton.FaceId = 17
' Set the focus to the combo box.
testComboBox.SetFocus

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarComboBox Events (Office)

 Copy code hover
[image]

CommandBarComboBox Events (Office)
Send feedback

Published: June 15, 2012

This object has the following events:

Events

Name | Description
Change | Occurs when the end user changes the selection in a CommandBar combo box.


CommandBarComboBox.Change Event (Office)

 Copy code hover
[image]

CommandBarComboBox.Change Event (Office)
See also Send feedback

Published: June 15, 2012

Occurs when the end user changes the selection in a CommandBar combo box.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Change(ByVal Ctrl As CommandBarComboBox)

expression A variable that represents a CommandBarComboBox object.

Parameters

Name | Required/Optional | Data Type | Description
Ctrl | Required | CommandBarComboBox | Represents a CommandBar combo box.

Remarks

The Change event is recognized by the CommandBarComboBox object. To return the Change event for a particular CommandBarComboBox control, use the WithEvents keyword to declare a variable, and then set the variable to the CommandBarComboBox control. When the Change event is triggered, it executes the macro or code that you specified with the OnAction property of the control.

Example

The following example creates a command bar with a CommandBarComboBox control containing four selections. The combo box responds to user interaction through the CommandBarComboBox_Change event.

Copy code Copy code
Private ctlComboBoxHandler As New ComboBoxHandler
Sub AddComboBox()

    Set HostApp = Application

    Dim newBar As Office.CommandBar
    Set newBar = HostApp.CommandBars.Add(Name:="Test CommandBar", Temporary:=True)
    Dim newCombo As Office.CommandBarComboBox
    Set newCombo = newBar.Controls.Add(msoControlComboBox)
    With newCombo
        .AddItem "First Class", 1
        .AddItem "Business Class", 2
        .AddItem "Coach Class", 3
        .AddItem "Standby", 4
        .DropDownLines = 5
        .DropDownWidth = 75
        .ListHeaderCount = 0
    End With
    ctlComboBoxHandler.SyncBox newCombo
    newBar.Visible = True

End Sub

The preceding example relies on the following code, which is stored in a class module in the VBA project.

Copy code Copy code
Private WithEvents ComboBoxEvent As Office.CommandBarComboBox
Public Sub SyncBox(box As Office.CommandBarComboBox)
    Set ComboBoxEvent = box
    If Not box Is Nothing Then
        MsgBox "Synced " & box.Caption & " ComboBox events."
    End If

End Sub

Private Sub Class_Terminate()
    Set ComboBoxEvent = Nothing
End Sub

Private Sub ComboBoxEvent_Change(ByVal Ctrl As Office.CommandBarComboBox)
    Dim stComboText As String

    stComboText = Ctrl.Text

        Select Case stComboText
        Case "First Class"
            FirstClass
        Case "Business Class"
            BusinessClass
        Case "Coach Class"
            CoachClass
        Case "Standby"
            Standby
    End Select

End Sub
Private Sub FirstClass()
    MsgBox "You selected First Class reservations"
End Sub
Private Sub BusinessClass()
    MsgBox "You selected Business Class reservations"
End Sub
Private Sub CoachClass()
    MsgBox "You selected Coach Class reservations"
End Sub
Private Sub Standby()
    MsgBox "You chose to fly standby"
End Sub

See also

Concepts

CommandBarComboBox Object

Other resources

CommandBarComboBox Object Members


CommandBarControl Object (Office)

 Copy code hover
[image]

CommandBarControl Object (Office)
See also Send feedback

Published: June 15, 2012

Represents a command bar control. The CommandBarControl object is a member of the CommandBarControls collection. The properties and methods of the CommandBarControl object are all shared by the CommandBarButton, CommandBarComboBox, and CommandBarPopup objects.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Remarks

When writing Visual Basic code to work with custom command bar controls, you use the CommandBarButton, CommandBarComboBox, and CommandBarPopup objects. When writing code to work with built-in controls in the container application that cannot be represented by one of those three objects, you use the CommandBarControl object. Use Controls(index), where index is the index number of a control, to return a CommandBarControl object. (The Type property of the control must be msoControlLabel, msoControlExpandingGrid, msoControlSplitExpandingGrid, msoControlGrid, or msoControlGauge). Variables declared as CommandBarControl can be assigned CommandBarButton, CommandBarComboBox, and CommandBarPopup values.

Example

You can also use the FindControl method to return a CommandBarControl object. The following example searches for a control of type msoControlGauge; if it finds one, it displays the index number of the control and the name of the command bar that contains it. In this example, the variable lbl represents a CommandBarControl object.

Copy code Copy code
Set lbl = CommandBars.FindControl(Type:= msoControlGauge)
If lbl Is Nothing Then
    MsgBox "A control of type msoControlGauge was not found."
Else
    MsgBox "Control " & lbl.Index & " on command bar " _
        & lbl.Parent.Name & " is type msoControlGauge"
End If

See also

Concepts

Object Model Reference

Other resources

CommandBarControl Object Members


CommandBarControl Members (Office)

 Copy code hover
[image]

CommandBarControl Members (Office)
Send feedback

Published: June 15, 2012

Represents a command bar control. The CommandBarControl object is a member of the CommandBarControls collection. The properties and methods of the CommandBarControl object are all shared by the CommandBarButton, CommandBarComboBox, and CommandBarPopup objects.

Methods

Name | Description
Copy | Copies a command bar control to an existing command bar.
Delete | Deletes the CommandBarControl object from its collection.
Execute | Runs the procedure or built-in command assigned to the specified CommandBarControl control.
Move | Moves the specified CommandBarControl to an existing command bar.
Reset | Resets a built-in command bar to its default configuration, or resets a built-in CommandBarControl to its original function and face.
SetFocus | Moves the keyboard focus to the specified CommandBarControl. If the control is disabled or isn't visible, this method will fail.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CommandBarControl object (you can use this property with an Automation object to return that object's container application). Read-only.
BeginGroup | Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.
BuiltIn | Gets True if the specified command bar control is a built-in control of the container application. Returns False if it's a custom control, or if it's a built-in control whose OnAction property has been set. Read-only.
Caption | Gets or sets the caption text for a command bar control. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBarControl object was created. Read-only.
DescriptionText | Gets or sets the description for a command bar control. Read/write.
Enabled | Gets or sets a Boolean value specifying if the CommandBarControl is enabled. Read/write.
Height | Gets or sets the height of a CommandBarControl control. Read/write.
HelpContextId | Gets or sets the Help context Id number for the Help topic attached to the CommandBarControl. Read/write.
HelpFile | Gets or sets the file name for the Help topic attached to the CommandBarControl. Read/write.
Id | Gets the ID for a built-in CommandBarControl. Read-only.
Index | Gets a Long representing the index number for a CommandBarControl object in the collection. Read-only.
IsPriorityDropped | Gets True if the control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.
Left | Gets the horizontal position of the specified CommandBarControl (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.
OLEUsage | Gets or sets the OLE client and OLE server roles in which a CommandBarControl will be used when two Microsoft Office applications are merged. Read/write.
OnAction | Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarControl. Read/write.
Parameter | Gets or sets a string that an application can use to execute a command from a CommandBarControl. Read/write.
Parent | Gets the Parent object for the CommandBarControl object. Read-only.
Priority | Gets or sets the priority of a CommandBarControl. A control's priority determines whether the control can be dropped from a docked command bar if the command bar controls can't fit in a single row. Controls that can't fit in a single row drop off command bars from right to left. Read/write.
Tag | Gets or sets information about the CommandBarControl, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.
TooltipText | Gets or sets the text displayed in a CommandBarControl's ScreenTip. Read/write.
Top | Gets the distance (in pixels) from the top edge of the specified CommandBarControl to the top edge of the screen. Read-only.
Type | Gets the type of CommandBarControl. Read-only.
Visible | Gets or sets the Visible property of the CommandBarControl. True if the CommandBarControl is visible. Read/write.
Width | Gets or sets the width (in pixels) of the specified CommandBarControl. Read/write.


CommandBarControl Properties (Office)

 Copy code hover
[image]

CommandBarControl Properties (Office)
Send feedback

Published: June 15, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CommandBarControl object (you can use this property with an Automation object to return that object's container application). Read-only.
BeginGroup | Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.
BuiltIn | Gets True if the specified command bar control is a built-in control of the container application. Returns False if it's a custom control, or if it's a built-in control whose OnAction property has been set. Read-only.
Caption | Gets or sets the caption text for a command bar control. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBarControl object was created. Read-only.
DescriptionText | Gets or sets the description for a command bar control. Read/write.
Enabled | Gets or sets a Boolean value specifying if the CommandBarControl is enabled. Read/write.
Height | Gets or sets the height of a CommandBarControl control. Read/write.
HelpContextId | Gets or sets the Help context Id number for the Help topic attached to the CommandBarControl. Read/write.
HelpFile | Gets or sets the file name for the Help topic attached to the CommandBarControl. Read/write.
Id | Gets the ID for a built-in CommandBarControl. Read-only.
Index | Gets a Long representing the index number for a CommandBarControl object in the collection. Read-only.
IsPriorityDropped | Gets True if the control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.
Left | Gets the horizontal position of the specified CommandBarControl (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.
OLEUsage | Gets or sets the OLE client and OLE server roles in which a CommandBarControl will be used when two Microsoft Office applications are merged. Read/write.
OnAction | Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarControl. Read/write.
Parameter | Gets or sets a string that an application can use to execute a command from a CommandBarControl. Read/write.
Parent | Gets the Parent object for the CommandBarControl object. Read-only.
Priority | Gets or sets the priority of a CommandBarControl. A control's priority determines whether the control can be dropped from a docked command bar if the command bar controls can't fit in a single row. Controls that can't fit in a single row drop off command bars from right to left. Read/write.
Tag | Gets or sets information about the CommandBarControl, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.
TooltipText | Gets or sets the text displayed in a CommandBarControl's ScreenTip. Read/write.
Top | Gets the distance (in pixels) from the top edge of the specified CommandBarControl to the top edge of the screen. Read-only.
Type | Gets the type of CommandBarControl. Read-only.
Visible | Gets or sets the Visible property of the CommandBarControl. True if the CommandBarControl is visible. Read/write.
Width | Gets or sets the width (in pixels) of the specified CommandBarControl. Read/write.


CommandBarControl.Application Property (Office)

 Copy code hover
[image]

CommandBarControl.Application Property (Office)
See also Send feedback

Published: June 15, 2012

Gets an Application object that represents the container application for the CommandBarControl object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Application

expression A variable that represents a CommandBarControl object.

Return Value

Object

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.BeginGroup Property (Office)

 Copy code hover
[image]

CommandBarControl.BeginGroup Property (Office)
See also Send feedback

Published: June 15, 2012

Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .BeginGroup

expression A variable that represents a CommandBarControl object.

Return Value

Boolean

Example

This example begins a new group with the last control on the active menu bar.

Copy code Copy code
Set myMenuBar = CommandBars.ActiveMenuBar
Set lastMenu = myMenuBar _
    .Controls(myMenuBar.Controls.Count)
lastMenu.BeginGroup = True

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.BuiltIn Property (Office)

 Copy code hover
[image]

CommandBarControl.BuiltIn Property (Office)
See also Send feedback

Published: June 15, 2012

Gets True if the specified command bar control is a built-in control of the container application. Returns False if it's a custom control, or if it's a built-in control whose OnAction property has been set. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .BuiltIn

expression A variable that represents a CommandBarControl object.

Return Value

Boolean

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Caption Property (Office)

 Copy code hover
[image]

CommandBarControl.Caption Property (Office)
See also Send feedback

Published: June 15, 2012

Gets or sets the caption text for a command bar control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Caption

expression A variable that represents a CommandBarControl object.

Return Value

String

Example

This example adds a command bar control with a spelling checker button face to a custom command bar, and then it sets the caption to "Spelling checker."

VBA Copy code Copy code
Set myBar = CommandBars.Add(Name:="Custom", _
Position:=msoBarTop, Temporary:=True)
myBar.Visible = True
Set myControl = myBar.Controls _
.Add(Type:=msoControlButton, Id:=2)
With myControl
    .DescriptionText = "Starts the spelling checker"
    .Caption = "Spelling checker"
End With
Note Note

Note Note

A control's caption is also displayed as its default ScreenTip.

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Creator Property (Office)

 Copy code hover
[image]

CommandBarControl.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CommandBarControl object was created. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Creator

expression A variable that represents a CommandBarControl object.

Return Value

Long

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.DescriptionText Property (Office)

 Copy code hover
[image]

CommandBarControl.DescriptionText Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the description for a command bar control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .DescriptionText

expression A variable that represents a CommandBarControl object.

Return Value

String

Remarks

The description is not displayed to the user, but it can be useful for documenting the behavior of the control for other developers.

Example

This example adds a control to a custom command bar, including a description of the control's behavior.

VBA Copy code Copy code
Set myBar = CommandBars.Add("Custom", msoBarTop, , True)
myBar.Visible = True
Set myControl = myBar.Controls _
    .Add(Type:=msoControlButton, ID:= _
    CommandBars("Standard").Controls("Paste").ID)
With myControl
    .DescriptionText = "Pastes the contents of the Clipboard"
    .Caption = "Paste"
End With

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Enabled Property (Office)

 Copy code hover
[image]

CommandBarControl.Enabled Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a Boolean value specifying if the CommandBarControl is enabled. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Enabled

expression A variable that represents a CommandBarControl object.

Remarks

For command bars, setting this property to True causes the name of the command bar to appear in the list of available command bars.

For built-in controls, if you set the Enabled property to True, the application determines its state, but setting it to False will force it to be disabled.

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Height Property (Office)

 Copy code hover
[image]

CommandBarControl.Height Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the height of a CommandBarControl control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Height

expression A variable that represents a CommandBarControl object.

Return Value

Integer

Example

This example adds a custom control to the command bar named Custom. The example sets the height of the custom control to twice the height of the command bar and sets the control's width to 50 pixels. Notice how the command bar automatically resizes itself to accommodate the control.

VBA Copy code Copy code
Set myBar = CommandBars("Custom")
barHeight = myBar.Height
Set myControl = myBar.Controls _
    .Add(Type:=msoControlButton, _
    Id:= CommandBars("Standard").Controls("Save").Id, _
     Temporary:=True)
With myControl
    .Height = barHeight * 2
    .Width = 50
End With
myBar.Visible = True

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.HelpContextId Property (Office)

 Copy code hover
[image]

CommandBarControl.HelpContextId Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the Help context Id number for the Help topic attached to the CommandBarControl. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .HelpContextId

expression A variable that represents a CommandBarControl object.

Return Value

Integer

Remarks

To use this property, you must also set the HelpFile property. Help topics respond to Shift+F1.

Example

This example adds a custom command bar with a combo box that tracks stock data. The example also specifies the Help topic to be displayed for the combo box when the user presses SHIFT+F1.

VBA Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
With myBar
    .Controls.Add Type:=msoControlComboBox, ID:=1
    .Visible = True
End With
With CommandBars("Custom").Controls(1)
    .AddItem "Get Stock Quote", 1
    .AddItem "View Chart", 2
    .AddItem "View Fundamentals", 3
    .AddItem "View News", 4
    .Caption = "Stock Data"
    .DescriptionText = "View Data For Stock"
    .HelpFile = "C:\corphelp\custom.hlp"
    .HelpContextID = 47
End With

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.HelpFile Property (Office)

 Copy code hover
[image]

CommandBarControl.HelpFile Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the file name for the Help topic attached to the CommandBarControl. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .HelpFile

expression A variable that represents a CommandBarControl object.

Return Value

String

Remarks

To use this property, you must also set the HelpContextID property. Help topics respond to the user pressing SHIFT+F1.

Example

This example adds a custom command bar with a combo box that tracks stock data. The example also specifies the Help topic to be displayed for the combo box when the user presses SHIFT+F1.

VBA Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
With myBar
    .Controls.Add Type:=msoControlComboBox, ID:=1
    .Visible = True
End With
With CommandBars("Custom").Controls(1)
    .AddItem "Get Stock Quote", 1
    .AddItem "View Chart", 2
    .AddItem "View Fundamentals", 3
    .AddItem "View News", 4
    .Caption = "Stock Data"
    .DescriptionText = "View Data For Stock"
    .HelpFile = "C:\corphelp\custom.hlp"
    .HelpContextID = 47
End With

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Id Property (Office)

 Copy code hover
[image]

CommandBarControl.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the ID for a built-in CommandBarControl. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Id

expression Required. A variable that represents a CommandBarControl object.

Remarks

A control's ID determines the built-in action for that control. The value of the Id property for all custom controls is 1.

Example

This example changes the button face of the first control on the command bar named "Custom2" if the button's Id value is less than 25.

VBA Copy code Copy code
Set ctrl = CommandBars("Custom").Controls(1)
With ctrl
    If .Id < 25 Then
        .FaceId = 17
        .Tag = "Changed control"
    End If
End With

The following example changes the caption of every control on the toolbar named "Standard" to the current value of the Id property for that control.

VBA Copy code Copy code
For Each ctl In CommandBars("Standard").Controls
    ctl.Caption = CStr(ctl.Id)
Next ctl

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Index Property (Office)

 Copy code hover
[image]

CommandBarControl.Index Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long representing the index number for a CommandBarControl object in the collection. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Index

expression A variable that represents a CommandBarControl object.

Return Value

Integer

Remarks

The position of the first command bar control is 1. Separators are not counted in the CommandBarControls collection.

Example

This example searches the command bar named "Custom2" for a control with an Id value of 23. If such a control is found and the index number of the control is greater than 5, the control will be positioned as the first control on the command bar.

VBA Copy code Copy code
Set myBar = CommandBars("Custom2")
Set ctrl1 = myBar.FindControl(Id:=23)
If ctrl1.Index > 5 Then
    ctrl1.Move before:=1
End If

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.IsPriorityDropped Property (Office)

 Copy code hover
[image]

CommandBarControl.IsPriorityDropped Property (Office)
See also Send feedback

Published: July 09, 2012

Gets True if the control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .IsPriorityDropped

expression A variable that represents a CommandBarControl object.

Return Value

Boolean

Remarks

A control with Visible set to True, will not be immediately visible on a personalized menu or toolbar if IsPriorityDropped is True.

To determine when to set IsPriorityDropped to True for a specific menu item, Microsoft Office maintains a total count of the number of times the menu item was used and a record of the number of different application sessions in which the user has used another menu item in the same menu as this menu item, without using the specific menu item. When this value reaches certain threshold values, the count is decremented. When the count reaches zero, IsPriorityDropped is set to True. Programmers cannot set the session value, the threshold value, or the IsPriorityDropped property. Programmers can, however, use the AdaptiveMenus property to disable adaptive menus for specific menus in an application.

To determine when to set IsPriorityDropped to True for a specific toolbar control, Office maintains a list of the order in which all the controls on that toolbar were last executed. A toolbar will always show as many controls as it has space to show, in the order of most recently used to least recently used. Controls with Priority set to 1 will always be shown and the toolbar will wrap rows, if necessary, to show these controls. Programmers can use the Priority property to ensure that specific toolbar controls are always shown, or to reposition toolbars so that they have enough space to display all of their controls.

You can use the following table to predict the number of sessions for which a menu item on a personalized menu will remain visible before the menu item's IsPriorityDropped property is set to True.

Number of uses of the command bar control | Number of sessions of the application
0, 1 | 3
2 | 6
3 | 9
4, 5 | 12
6- 8 | 17
9-13 | 23
14-24 | 29
25 or more | 31

Example

This example checks the IsPriorityDropped property for the first control on the command bar named "Custom." If IsPriorityDropped is True, the example sets the AdaptiveMenus property to False, restoring the dropped command bar.

VBA Copy code Copy code
If CommandBars("Custom").Controls(1).IsPriorityDropped Then
    CommandBars.AdaptiveMenus = True
End If

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Left Property (Office)

 Copy code hover
[image]

CommandBarControl.Left Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the horizontal position of the specified CommandBarControl (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Left

expression Required. A variable that represents a CommandBarControl object.

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.OLEUsage Property (Office)

 Copy code hover
[image]

CommandBarControl.OLEUsage Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the OLE client and OLE server roles in which a CommandBarControl will be used when two Microsoft Office applications are merged. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .OLEUsage

expression A variable that represents a CommandBarControl object.

Return Value

MsoControlOLEUsage

Remarks

This property is intended to allow you to specify how individual add-in applications' command bar controls are represented in one Office application when it is merged with another Office application. If both the client and server implement command bars, the command bar controls are embedded in the client control by control. Custom controls marked as client-only (or neither client nor server) are dropped from the server, and controls marked as server-only (or neither server nor client) are dropped from the client. The remaining controls are merged.

If one of the merging applications is not an Office application, normal OLE menu merging is used, which is controlled by the OLEMenuGroup property.

Example

This example adds a new button to the command bar named "Tools", and sets its OLEUsage property.

VBA Copy code Copy code
Set myControl = CommandBars("Tools").Controls _
    .Add(Type:=msoControlButton,Temporary:=True)
myControl.OLEUsage = msoControlOLEUsageNeither

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.OnAction Property (Office)

 Copy code hover
[image]

CommandBarControl.OnAction Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarControl. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .OnAction

expression A variable that represents a CommandBarControl object.

Return Value

String

Remarks

The container application determines whether the value is a valid macro name.

Example

This example adds a command bar control to the command bar named "Custom". The procedure named MySub will run each time the control is clicked.

VBA Copy code Copy code
Set myBar = CommandBars("Custom")
Set myControl = myBar.Controls _
    .Add(Type:=msocontrolButton)
With myControl
    .FaceId = 2
    .OnAction = "MySub"
End With
myBar.Visible = True

This example adds a command bar control to the command bar named "Custom". The COM add-in named "FinanceAddIn" will run each time the control is clicked.

VBA Copy code Copy code
Set myBar = CommandBars("Custom")
Set myControl = myBar.Controls _
    .Add(Type:=msocontrolButton)
With myControl
    .FaceId = 2
    .OnAction = "!<FinanceAddIn>"
End With
myBar.Visible = True

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Parameter Property (Office)

 Copy code hover
[image]

CommandBarControl.Parameter Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a string that an application can use to execute a command from a CommandBarControl. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Parameter

expression A variable that represents a CommandBarControl object.

Return Value

String

Remarks

If the specified parameter is set for a built-in control, the application can modify its default behavior if it can parse and use the new value. If the parameter is set for custom controls, it can be used to send information to Visual Basic procedures, or it can be used to hold information about the control (similar to a second Tag property value).

Example

This example assigns a new parameter to a control and sets the focus to the new button.

VBA Copy code Copy code
Set myControl = CommandBars("Custom").Controls(4)
With myControl
    .Copy , 1
    .Parameter = "2"
    .SetFocus
End With

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Parent Property (Office)

 Copy code hover
[image]

CommandBarControl.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CommandBarControl object. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Parent

expression A variable that represents a CommandBarControl object.

Return Value

CommandBar

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Priority Property (Office)

 Copy code hover
[image]

CommandBarControl.Priority Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the priority of a CommandBarControl. A control's priority determines whether the control can be dropped from a docked command bar if the command bar controls can't fit in a single row. Controls that can't fit in a single row drop off command bars from right to left. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Priority

expression A variable that represents a CommandBarControl object.

Remarks

Valid priority numbers are 0 (zero) through 7 and the default value is 3. A priority of 1 means that the control cannot be dropped from a toolbar. Other priority values are ignored.

The Priority property is not used by command bar controls that are menu items.

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Tag Property (Office)

 Copy code hover
[image]

CommandBarControl.Tag Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets information about the CommandBarControl, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Tag

expression A variable that represents a CommandBarControl object.

Return Value

String

Example

To avoid duplicate calls of the same class when tiggered with events, define the Tag property unique to the events. The following example demonstrates this concept with two modules.

VBA Copy code Copy code
Public WithEvents oBtn As CommandBarButton

Private Sub oBtn_click(ByVal ctrl As Office.CommandBarButton, CancelDefault As Boolean)
    MsgBox "Clicked " & ctrl.Caption

End Sub

Dim oBtns As New Collection

Sub Use_Tag()

    Dim oEvt As CBtnEvent
    Set oBtns = Nothing

    For i = 1 To 5
        Set oEvt = New CBtnEvent
        Set oEvt.oBtn = Application.CommandBars("Worksheet Menu Bar").Controls.Add(msoControlButton)
        With oEvt.oBtn
            .Caption = "Btn" & i
            .Style = msoButtonCaption
            .Tag = "Hello" & i
        End With
        oBtns.Add oEvt
    Next

End Sub

This example sets the tag for the button on the custom command bar to "Spelling Button" and displays the tag in a message box.

Copy code Copy code
CommandBars("Custom").Controls(1).Tag = "Spelling Button"
MsgBox (CommandBars("Custom").Controls(1).Tag)

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.TooltipText Property (Office)

 Copy code hover
[image]

CommandBarControl.TooltipText Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the text displayed in a CommandBarControl's ScreenTip. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .TooltipText

expression A variable that represents a CommandBarControl object.

Return Value

String

Remarks

By default, the value of the Caption property is used as the ScreenTip.

Example

This example adds a ScreenTip to the last control on the active menu bar.

Copy code Copy code
Set myMenuBar = CommandBars.ActiveMenuBar
Set lastCtrl = myMenuBar _
   .Controls(myMenuBar.Controls.Count)
lastCtrl.BeginGroup = True
lastCtrl.TooltipText = "Click for help on UI feature"

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Top Property (Office)

 Copy code hover
[image]

CommandBarControl.Top Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the distance (in pixels) from the top edge of the specified CommandBarControl to the top edge of the screen. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Top

expression Required. A variable that represents a CommandBarControl object.

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Type Property (Office)

 Copy code hover
[image]

CommandBarControl.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the type of CommandBarControl. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Type

expression Required. A variable that represents a CommandBarControl object.

Remarks

The value of the Type property is available as a value in the MsoControlType enumeration.

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Visible Property (Office)

 Copy code hover
[image]

CommandBarControl.Visible Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the Visible property of the CommandBarControl. True if the CommandBarControl is visible. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Visible

expression A variable that represents a CommandBarControl object.

Return Value

Boolean

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Width Property (Office)

 Copy code hover
[image]

CommandBarControl.Width Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the width (in pixels) of the specified CommandBarControl. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Width

expression A variable that represents a CommandBarControl object.

Return Value

Integer

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl Methods (Office)

 Copy code hover
[image]

CommandBarControl Methods (Office)
Send feedback

Published: June 15, 2012

This object has the following methods:

Methods

Name | Description
Copy | Copies a command bar control to an existing command bar.
Delete | Deletes the CommandBarControl object from its collection.
Execute | Runs the procedure or built-in command assigned to the specified CommandBarControl control.
Move | Moves the specified CommandBarControl to an existing command bar.
Reset | Resets a built-in command bar to its default configuration, or resets a built-in CommandBarControl to its original function and face.
SetFocus | Moves the keyboard focus to the specified CommandBarControl. If the control is disabled or isn't visible, this method will fail.


CommandBarControl.Copy Method (Office)

 Copy code hover
[image]

CommandBarControl.Copy Method (Office)
See also Send feedback

Published: July 09, 2012

Copies a command bar control to an existing command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Copy(Bar, Before)

expression A variable that represents a CommandBarControl object.

Parameters

Name | Required/Optional | Data Type | Description
Bar | Optional | Variant | A CommandBar object that represents the destination command bar. If this argument is omitted, the control is copied to the command bar where the control already exists.
Before | Optional | Variant | A number that indicates the position for the new control on the command bar. The new control will be inserted before the control at this position. If this argument is omitted, the control is copied to the end of the command bar.

Return Value

CommandBarControl

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Delete Method (Office)

 Copy code hover
[image]

CommandBarControl.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the CommandBarControl object from its collection.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Delete(Temporary)

expression Required. A variable that represents a CommandBarControl object.

Parameters

Name | Required/Optional | Data Type | Description
Temporary | Optional | Variant | True to delete the control for the current session. The application will display the control again in the next session.

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Execute Method (Office)

 Copy code hover
[image]

CommandBarControl.Execute Method (Office)
See also Send feedback

Published: July 09, 2012

Runs the procedure or built-in command assigned to the specified CommandBarControl control.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Execute

expression Required. A variable that represents a CommandBarControl object.

Example

This Microsoft Excel example creates a command bar and then adds a built-in command bar button control to it. The button executes the Excel AutoSum function. This example uses the Execute method to total the selected range of cells when the command bar appears.

VBA Copy code Copy code
Dim cbrCustBar As CommandBar
Dim ctlAutoSum As CommandBarButton
Set cbrCustBar = CommandBars.Add("Custom")
Set ctlAutoSum = cbrCustBar.Controls _
    .Add(msoControlButton, CommandBars("Standard") _
    .Controls("AutoSum").Id)
cbrCustBar.Visible = True
ctlAutoSum.Execute

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Move Method (Office)

 Copy code hover
[image]

CommandBarControl.Move Method (Office)
See also Send feedback

Published: July 09, 2012

Moves the specified CommandBarControl to an existing command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Move(Bar, Before)

expression Required. A variable that represents a CommandBarControl object.

Parameters

Name | Required/Optional | Data Type | Description
Bar | Optional | Variant | A Command object that represents the destination command bar for the control. If this argument is omitted, the control is moved to the end of the command bar where the control currently resides.
Before | Optional | Variant | A number that indicates the position for the control. The control is inserted before the control currently occupying this position. If this argument is omitted, the control is inserted on the same command bar.

Example

This example moves the first combo box control on the command bar named Custom to the position before the seventh control on that command bar. The example sets the tag to "Selection box" and assigns the control a low priority so that it will likely be dropped from the command bar if all the controls don't fit in one row.

VBA Copy code Copy code
Set allcontrols = CommandBars("Custom").Controls
For Each ctrl In allControls
    If ctrl.Type = msoControlComboBox Then
        With ctrl
            .Move Before:=7
             .Tag = "Selection box"
             .Priority = 5
         End With
         Exit For
    End If
Next

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.Reset Method (Office)

 Copy code hover
[image]

CommandBarControl.Reset Method (Office)
See also Send feedback

Published: July 09, 2012

Resets a built-in command bar to its default configuration, or resets a built-in CommandBarControl to its original function and face.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Reset

expression A variable that represents a CommandBarControl object.

Remarks

Resetting a built-in control restores the actions originally intended for the control and resets each of the control's properties back to its original state. Resetting a built-in command bar removes custom controls and restores built-in controls.

Example

This example uses the value of user to adjust the command bars according to the user level. If user is "Level 1," the command bar named "Custom" is displayed. If user is any other value, the built-in Visual Basic command bar is reset to its default state and the command bar named "Custom" is disabled.

VBA Copy code Copy code
Set myBarControl = CommandBars("Custom").Controls(2)
If user = "Level 1" Then
    myBarControl.Visible = True
Else
    CommandBars("Visual Basic").Reset
    myBarControl.Enabled = False
End If

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControl.SetFocus Method (Office)

 Copy code hover
[image]

CommandBarControl.SetFocus Method (Office)
See also Send feedback

Published: July 09, 2012

Moves the keyboard focus to the specified CommandBarControl. If the control is disabled or isn't visible, this method will fail.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .SetFocus

expression A variable that represents a CommandBarControl object.

Remarks

The focus on the control is subtle. After you use this method, you will notice a three dimensional highlight on the control. Pressing the arrow keys will navigate in the toolbars, as if you had arrived at the control by pressing only keyboard controls.

Example

This example creates a command bar named "Custom" and adds a ComboBox control and a Button control to it. The example then uses the SetFocus method to set the focus to the ComboBox control.

VBA Copy code Copy code
Set focusBar = CommandBars.Add(Name:="Custom")
With CommandBars("Custom")
    .Visible = True
    .Position = msoBarTop
End With

Set testComboBox = CommandBars("Custom").Controls _
    .Add(Type:=msoControlComboBox, ID:=1)
With testComboBox
    .AddItem "First Item", 1
    .AddItem "Second Item", 2
End With
Set testButton = CommandBars("Custom").Controls _
    .Add(Type:=msoControlButton)
testButton.FaceId = 17
' Set the focus to the combo box.
testComboBox.SetFocus

See also

Concepts

CommandBarControl Object

Other resources

CommandBarControl Object Members


CommandBarControls Object (Office)

 Copy code hover
[image]

CommandBarControls Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of CommandBarControl objects that represent the command bar controls on a command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Example

Use the Controls property to return the CommandBarControls collection. The following example changes the caption of every control on the toolbar named "Standard" to the current value of the Id property for that control.

Copy code Copy code
For Each ctl In CommandBars("Standard").Controls
    ctl.Caption = CStr(ctl.Id)
Next ctl

Use the Add method to add a new command bar control to the CommandBarControls collection. This example adds a new, blank button to the command bar named "Custom."

Copy code Copy code
Set myBlankBtn = CommandBars("Custom").Controls.Add

Use Controls(index), where index is the caption or index number of a control, to return a CommandBarControl, CommandBarButton, CommandBarComboBox, or CommandBarPopup object. The following example copies the first control from the command bar named "Standard" to the command bar named "Custom."

Copy code Copy code
Set myCustomBar = CommandBars("Custom")
Set myControl = CommandBars("Standard").Controls(1)
myControl.Copy Bar:=myCustomBar, Before:=1

See also

Concepts

Object Model Reference

Other resources

CommandBarControls Object Members


CommandBarControls Members (Office)

 Copy code hover
[image]

CommandBarControls Members (Office)
Send feedback

Published: July 09, 2012

A collection of CommandBarControl objects that represent the command bar controls on a command bar.

Methods

Name | Description
Add | Creates a new CommandBarControl object and adds it to the collection of controls on the specified command bar.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CommandBarControls object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a count of the numbers of controls on a command bar. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBarControls object was created. Read-only.
Item | Gets a CommandBarControl object from the CommandBarControls collection. Read-only.
Parent | Gets the Parent object for the CommandBarControls object. Read-only.


CommandBarControls Properties (Office)

 Copy code hover
[image]

CommandBarControls Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CommandBarControls object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a count of the numbers of controls on a command bar. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBarControls object was created. Read-only.
Item | Gets a CommandBarControl object from the CommandBarControls collection. Read-only.
Parent | Gets the Parent object for the CommandBarControls object. Read-only.


CommandBarControls.Application Property (Office)

 Copy code hover
[image]

CommandBarControls.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the CommandBarControls object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Application

expression A variable that represents a CommandBarControls object.

Return Value

Object

See also

Concepts

CommandBarControls Object

Other resources

CommandBarControls Object Members


CommandBarControls.Count Property (Office)

 Copy code hover
[image]

CommandBarControls.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a count of the numbers of controls on a command bar. Read-only.

Syntax

expression .Count

expression An expression that returns a CommandBarControls object.

Return Value

Integer

See also

Concepts

CommandBarControls Object

Other resources

CommandBarControls Object Members


CommandBarControls.Creator Property (Office)

 Copy code hover
[image]

CommandBarControls.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CommandBarControls object was created. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Creator

expression A variable that represents a CommandBarControls object.

Return Value

Long

See also

Concepts

CommandBarControls Object

Other resources

CommandBarControls Object Members


CommandBarControls.Item Property (Office)

 Copy code hover
[image]

CommandBarControls.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CommandBarControl object from the CommandBarControls collection. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Item(Index)

expression Required. A variable that represents a CommandBarControls object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | The name or index number of the object to be returned.

See also

Concepts

CommandBarControls Object

Other resources

CommandBarControls Object Members


CommandBarControls.Parent Property (Office)

 Copy code hover
[image]

CommandBarControls.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CommandBarControls object. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Parent

expression A variable that represents a CommandBarControls object.

Return Value

CommandBar

See also

Concepts

CommandBarControls Object

Other resources

CommandBarControls Object Members


CommandBarControls Methods (Office)

 Copy code hover
[image]

CommandBarControls Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Creates a new CommandBarControl object and adds it to the collection of controls on the specified command bar.


CommandBarControls.Add Method (Office)

 Copy code hover
[image]

CommandBarControls.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Creates a new CommandBarControl object and adds it to the collection of controls on the specified command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Add(Type, Id, Parameter, Before, Temporary)

expression Required. A variable that represents a CommandBarControls object.

Parameters

Name | Required/Optional | Data Type | Description
Type | Optional | Variant | The type of control to be added to the specified command bar. Can be one of the following MsoControl constants: msoControlButton, msoControlEdit, msoControlDropdown, msoControlComboBox, or msoControlPopup.
Id | Optional | Variant | An integer that specifies a built-in control. If the value of this argument is 1, or if this argument is omitted, a blank custom control of the specified type will be added to the command bar.
Parameter | Optional | Variant | For built-in controls, this argument is used by the container application to run the command. For custom controls, you can use this argument to send information to Visual Basic procedures, or you can use it to store information about the control (similar to a second Tag property value).
Before | Optional | Variant | A number that indicates the position of the new control on the command bar. The new control will be inserted before the control at this position. If this argument is omitted, the control is added at the end of the specified command bar.
Temporary | Optional | Variant | True to make the new control temporary. controls are automatically deleted when the container application is closed. The default value is False.

Example

This example creates a custom editing toolbar that contains buttons (controls) for cutting, copying, and pasting.

VBA Copy code Copy code
Dim customBar As CommandBar
Dim newButton As CommandBarButton
Set customBar = CommandBars.Add("Custom")
Set newButton = customBar.Controls _
    .Add(msoControlButton, CommandBars("Edit") _
    .Controls("Cut").Id)
Set newButton = customBar.Controls _
    .Add(msoControlButton, CommandBars("Edit") _
    .Controls("Copy").Id)
Set newButton = customBar.Controls _
    .Add(msoControlButton, CommandBars("Edit") _
    .Controls("Paste").Id)
customBar.Visible = True

See also

Concepts

CommandBarControls Object

Other resources

CommandBarControls Object Members


CommandBarPopup Object (Office)

 Copy code hover
[image]

CommandBarPopup Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a pop-up control on a command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Remarks

Every pop-up control contains a CommandBar object. To return the command bar from a pop-up control, apply the CommandBar property to the CommandBarPopup object.

Use Controls(index), where index is the number of the control, to return a CommandBarPopup object. Note that the Type property of the control must be msoControlPopup, msoControlGraphicPopup, msoControlButtonPopup, msoControlSplitButtonPopup, or msoControlSplitButtonMRUPopup.

Example

You can also use the FindControl method to return a CommandBarPopup object. The following example searches all command bars for a CommandBarPopup object whose tag is "Graphics."

Copy code Copy code
Set myControl = Application.CommandBars.FindControl _
(Type:=msoControlPopup, Tag:="Graphics")

See also

Concepts

Object Model Reference

Other resources

CommandBarPopup Object Members


CommandBarPopup Members (Office)

 Copy code hover
[image]

CommandBarPopup Members (Office)
Send feedback

Published: July 09, 2012

Represents a pop-up control on a command bar.

Methods

Name | Description
Copy | Copies a command bar popup control to an existing command bar.
Delete | Deletes the CommandBarPopup object from its collection.
Execute | Runs the procedure or built-in command assigned to the specified CommandBarPopup control.
Move | Moves the specified CommandBarPopup control to an existing command bar.
Reset | Resets a built-in CommandBarPopup control to its original function and face.
SetFocus | Moves the keyboard focus to the specified CommandBarPopup control. If the popup is disabled or isn't visible, this method will fail.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CommandBarPopup object (you can use this property with an Automation object to return that object's container application). Read-only.
BeginGroup | Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.
BuiltIn | Is True if the specified command bar popup is a built-in command bar of the container application. Returns False if it's a custom command bar. Read-only.
Caption | Gets or sets the caption text for a command bar control. Read/write.
CommandBar | Gets a CommandBar object that represents the menu displayed by the specified pop-up control. Read-only.
Controls | Gets a CommandBarControls object that represents all the controls on a pop-up control. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBarPopup object was created. Read-only.
DescriptionText | Gets or sets the description for a command barpopup control. Read/write.
Enabled | Is True if the CommandBarPopup is enabled. Read/write.
Height | Gets or sets the height of a CommandBarPopup control. Read/write.
HelpContextId | Gets or sets the Help context Id number for the Help topic attached to the CommandBarPopup control. Read/write.
HelpFile | Gets or sets the file name for the Help topic attached to the CommandBarPopup control. Read/write.
Id | Gets the ID for a built-in CommandBarPopup control. Read-only.
Index | Gets a Long representing the index number for a CommandBarPopup object in the collection. Read-only.
IsPriorityDropped | GetsTrue if the CommandBarPopup control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.
Left | Gets the horizontal position of the specified CommandBarPopup control (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.
OLEMenuGroup | Gets or sets a MsoOLEMenuGroup constant that represents the menu group that the specified command bar pop-up control belongs to when the menu groups of the OLE server are merged with the menu groups of an OLE client (that is, when an object of the container application type is embedded in another application). Read/write.
OLEUsage | Gets or sets the OLE client and OLE server roles in which a CommandBarPopup control is used when two Microsoft Office applications are merged. Read/write.
OnAction | Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarPopup control. Read/write.
Parameter | Gets or sets a string that an application can use to execute a command from a CommandBarPopup control. Read/write.
Parent | Gets the Parent object for the CommandBarPopup object. Read-only.
Priority | Gets or sets the priority of a CommandBarPopup control. Read/write.
Tag | Gets or sets information about the CommandBarPopup control, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.
TooltipText | Gets or sets the text displayed in a CommandBarPopup's ScreenTip. Read/write.
Top | Gets the distance (in pixels) from the top edge of the specified CommandBarPopup control to the top edge of the screen. Read-only.
Type | Gets the type of CommandBarPopup control. Read-only.
Visible | Gets or sets the Visible property of the CommandBarPopup control. Read/write.
Width | Gets or sets the width (in pixels) of the specified CommandBarPopup control. Read/write.


CommandBarPopup Properties (Office)

 Copy code hover
[image]

CommandBarPopup Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CommandBarPopup object (you can use this property with an Automation object to return that object's container application). Read-only.
BeginGroup | Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.
BuiltIn | Is True if the specified command bar popup is a built-in command bar of the container application. Returns False if it's a custom command bar. Read-only.
Caption | Gets or sets the caption text for a command bar control. Read/write.
CommandBar | Gets a CommandBar object that represents the menu displayed by the specified pop-up control. Read-only.
Controls | Gets a CommandBarControls object that represents all the controls on a pop-up control. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBarPopup object was created. Read-only.
DescriptionText | Gets or sets the description for a command barpopup control. Read/write.
Enabled | Is True if the CommandBarPopup is enabled. Read/write.
Height | Gets or sets the height of a CommandBarPopup control. Read/write.
HelpContextId | Gets or sets the Help context Id number for the Help topic attached to the CommandBarPopup control. Read/write.
HelpFile | Gets or sets the file name for the Help topic attached to the CommandBarPopup control. Read/write.
Id | Gets the ID for a built-in CommandBarPopup control. Read-only.
Index | Gets a Long representing the index number for a CommandBarPopup object in the collection. Read-only.
IsPriorityDropped | GetsTrue if the CommandBarPopup control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.
Left | Gets the horizontal position of the specified CommandBarPopup control (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.
OLEMenuGroup | Gets or sets a MsoOLEMenuGroup constant that represents the menu group that the specified command bar pop-up control belongs to when the menu groups of the OLE server are merged with the menu groups of an OLE client (that is, when an object of the container application type is embedded in another application). Read/write.
OLEUsage | Gets or sets the OLE client and OLE server roles in which a CommandBarPopup control is used when two Microsoft Office applications are merged. Read/write.
OnAction | Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarPopup control. Read/write.
Parameter | Gets or sets a string that an application can use to execute a command from a CommandBarPopup control. Read/write.
Parent | Gets the Parent object for the CommandBarPopup object. Read-only.
Priority | Gets or sets the priority of a CommandBarPopup control. Read/write.
Tag | Gets or sets information about the CommandBarPopup control, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.
TooltipText | Gets or sets the text displayed in a CommandBarPopup's ScreenTip. Read/write.
Top | Gets the distance (in pixels) from the top edge of the specified CommandBarPopup control to the top edge of the screen. Read-only.
Type | Gets the type of CommandBarPopup control. Read-only.
Visible | Gets or sets the Visible property of the CommandBarPopup control. Read/write.
Width | Gets or sets the width (in pixels) of the specified CommandBarPopup control. Read/write.


CommandBarPopup.Application Property (Office)

 Copy code hover
[image]

CommandBarPopup.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the CommandBarPopup object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Application

expression A variable that represents a CommandBarPopup object.

Return Value

Object

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.BeginGroup Property (Office)

 Copy code hover
[image]

CommandBarPopup.BeginGroup Property (Office)
See also Send feedback

Published: July 09, 2012

Gets True if the specified command bar control appears at the beginning of a group of controls on the command bar. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .BeginGroup

expression A variable that represents a CommandBarPopup object.

Return Value

Boolean

Example

This example begins a new group with the last control on the active menu bar.

Copy code Copy code
Set myMenuBar = CommandBars.ActiveMenuBar
Set lastMenu = myMenuBar _
    .Controls(myMenuBar.Controls.Count)
lastMenu.BeginGroup = True

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.BuiltIn Property (Office)

 Copy code hover
[image]

CommandBarPopup.BuiltIn Property (Office)
See also Send feedback

Published: July 09, 2012

Is True if the specified command bar popup is a built-in command bar of the container application. Returns False if it's a custom command bar. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .BuiltIn

expression A variable that represents a CommandBarPopup object.

Return Value

Boolean

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Caption Property (Office)

 Copy code hover
[image]

CommandBarPopup.Caption Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the caption text for a command bar control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Caption

expression A variable that represents a CommandBarPopup object.

Return Value

String

Example

This example adds a command bar control with a spelling checker button face to a custom command bar, and then it sets the caption to "Spelling checker."

VBA Copy code Copy code
Set myBar = CommandBars.Add(Name:="Custom", _
Position:=msoBarTop, Temporary:=True)
myBar.Visible = True
Set myControl = myBar.Controls _
.Add(Type:=msoControlButton, Id:=2)
With myControl
    .DescriptionText = "Starts the spelling checker"
    .Caption = "Spelling checker"
End With
Note Note

Note Note

A control's caption is also displayed as its default ScreenTip.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.CommandBar Property (Office)

 Copy code hover
[image]

CommandBarPopup.CommandBar Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CommandBar object that represents the menu displayed by the specified pop-up control. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .CommandBar

expression A variable that represents a CommandBarPopup object.

Example

This example sets the variable fourthLevel to the fourth control on the command bar named "Drawing."

Copy code Copy code
Set fourthLevel = CommandBars("Drawing") _
    .Controls(1).CommandBar.Controls(4)

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Controls Property (Office)

 Copy code hover
[image]

CommandBarPopup.Controls Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CommandBarControls object that represents all the controls on a pop-up control. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Controls

expression A variable that represents a CommandBarPopup object.

Return Value

CommandBarControls

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Creator Property (Office)

 Copy code hover
[image]

CommandBarPopup.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CommandBarPopup object was created. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Creator

expression A variable that represents a CommandBarPopup object.

Return Value

Long

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.DescriptionText Property (Office)

 Copy code hover
[image]

CommandBarPopup.DescriptionText Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the description for a command barpopup control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .DescriptionText

expression A variable that represents a CommandBarPopup object.

Return Value

String

Remarks

The description is not displayed to the user, but it can be useful for documenting the behavior of the control for other developers.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Enabled Property (Office)

 Copy code hover
[image]

CommandBarPopup.Enabled Property (Office)
See also Send feedback

Published: July 09, 2012

Is True if the CommandBarPopup is enabled. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Enabled

expression A variable that represents a CommandBarPopup object.

Return Value

Boolean

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Height Property (Office)

 Copy code hover
[image]

CommandBarPopup.Height Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the height of a CommandBarPopup control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Height

expression A variable that represents a CommandBarPopup object.

Return Value

Integer

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.HelpContextId Property (Office)

 Copy code hover
[image]

CommandBarPopup.HelpContextId Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the Help context Id number for the Help topic attached to the CommandBarPopup control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .HelpContextId

expression A variable that represents a CommandBarPopup object.

Return Value

Integer

Remarks

To use this property, you must also set the HelpFile property. Help topics respond to Shift+F1.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.HelpFile Property (Office)

 Copy code hover
[image]

CommandBarPopup.HelpFile Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the file name for the Help topic attached to the CommandBarPopup control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .HelpFile

expression A variable that represents a CommandBarPopup object.

Return Value

String

Remarks

To use this property, you must also set the HelpContextID property. Help topics respond to the user pressing SHIFT+F1.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Id Property (Office)

 Copy code hover
[image]

CommandBarPopup.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the ID for a built-in CommandBarPopup control. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Id

expression A variable that represents a CommandBarPopup object.

Return Value

Integer

Remarks

A popup's ID determines the built-in action for that object.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Index Property (Office)

 Copy code hover
[image]

CommandBarPopup.Index Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long representing the index number for a CommandBarPopup object in the collection. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Index

expression A variable that represents a CommandBarPopup object.

Return Value

Long

Remarks

The position of the first command bar control is 1. Separators are not counted in the CommandBarControls collection.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.IsPriorityDropped Property (Office)

 Copy code hover
[image]

CommandBarPopup.IsPriorityDropped Property (Office)
See also Send feedback

Published: July 09, 2012

GetsTrue if the CommandBarPopup control is currently dropped from the menu or toolbar based on usage statistics and layout space. (Note that this is not the same as the control's visibility, as set by the Visible property). Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .IsPriorityDropped

expression A variable that represents a CommandBarPopup object.

Return Value

Boolean

Remarks

A control with Visible set to True, will not be immediately visible on a personalized menu or toolbar if IsPriorityDropped is True.

To determine when to set IsPriorityDropped to True for a specific menu item, Microsoft Office maintains a total count of the number of times the menu item was used and a record of the number of different application sessions in which the user has used another menu item in the same menu as this menu item, without using the specific menu item. When this value reaches certain threshold values, the count is decremented. When the count reaches zero, IsPriorityDropped is set to True. Programmers cannot set the session value, the threshold value, or the IsPriorityDropped property. Programmers can, however, use the AdaptiveMenus property to disable adaptive menus for specific menus in an application.

To determine when to set IsPriorityDropped to True for a specific toolbar control, Office maintains a list of the order in which all the controls on that toolbar were last executed. A toolbar will always show as many controls as it has space to show, in the order of most recently used to least recently used. Controls with Priority set to 1 will always be shown and the toolbar will wrap rows, if necessary, to show these controls. Programmers can use the Priority property to ensure that specific toolbar controls are always shown, or to reposition toolbars so that they have enough space to display all of their controls.

You can use the following table to predict the number of sessions for which a menu item on a personalized menu will remain visible before the menu item's IsPriorityDropped property is set to True.

Number of uses of the command bar control | Number of sessions of the application
0, 1 | 3
2 | 6
3 | 9
4, 5 | 12
6- 8 | 17
9-13 | 23
14-24 | 29
25 or more | 31

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Left Property (Office)

 Copy code hover
[image]

CommandBarPopup.Left Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the horizontal position of the specified CommandBarPopup control (in pixels) relative to the left edge of the screen. Returns the distance from the left side of the docking area. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Left

expression Required. A variable that represents a CommandBarPopup object.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.OLEMenuGroup Property (Office)

 Copy code hover
[image]

CommandBarPopup.OLEMenuGroup Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a MsoOLEMenuGroup constant that represents the menu group that the specified command bar pop-up control belongs to when the menu groups of the OLE server are merged with the menu groups of an OLE client (that is, when an object of the container application type is embedded in another application). Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .OLEMenuGroup

expression A variable that represents a CommandBarPopup object.

Remarks

Note Note

This property is read-only for built-in controls.

This property is intended to allow add-in applications to specify how their command bar controls will be represented in the Office application. If either the container or the server does not implement command bars, normal OLE menu merging occurs: the menu bar is merged, and all the toolbars from the server, and none of the toolbars from the container. This property is relevant only for pop-up controls on the menu bar because menus are merged on the basis of their menu group category.

If both of the merging applications implement command bars, command bar controls are merged according to the OLEUsage property.

Example

This example checks the OLEMenuGroup property of a new custom pop-up control on the command bar named "Custom" and sets the property to msoOLEMenuGroupNone.

Copy code Copy code
Set myControl = CommandBars("Custom").Controls _
    .Add(Type:=msoControlPopup,Temporary:=False)
myControl.OLEMenuGroup = msoOLEMenuGroupNone

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.OLEUsage Property (Office)

 Copy code hover
[image]

CommandBarPopup.OLEUsage Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the OLE client and OLE server roles in which a CommandBarPopup control is used when two Microsoft Office applications are merged. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .OLEUsage

expression A variable that represents a CommandBarPopup object.

Return Value

MsoControlOLEUsage

Remarks

This property is intended to allow you to specify how individual add-in applications' command bar controls are represented in one Office application when it is merged with another Office application. If both the client and server implement command bars, the command bar controls are embedded in the client control by control. Custom controls marked as client-only (or neither client nor server) are dropped from the server, and controls marked as server-only (or neither server nor client) are dropped from the client. The remaining controls are merged.

If one of the merging applications is not an Office application, normal OLE menu merging is used, which is controlled by the OLEMenuGroup property.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.OnAction Property (Office)

 Copy code hover
[image]

CommandBarPopup.OnAction Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the name of a Visual Basic procedure that will run when the user clicks or changes the value of a CommandBarPopup control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .OnAction

expression A variable that represents a CommandBarPopup object.

Return Value

String

Remarks

The container application determines whether the value is a valid macro name.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Parameter Property (Office)

 Copy code hover
[image]

CommandBarPopup.Parameter Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a string that an application can use to execute a command from a CommandBarPopup control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Parameter

expression A variable that represents a CommandBarPopup object.

Return Value

String

Remarks

If the specified parameter is set for a built-in control, the application can modify its default behavior if it can parse and use the new value. If the parameter is set for custom controls, you can use it to send information to Visual Basic procedures, or you can use it to hold information about the control (similar to a second Tag property value).

Example

This example assigns a new parameter to a control and sets the focus to the new button.

VBA Copy code Copy code
Set myControl = CommandBars("Custom").Controls(4)
With myControl
    .Copy , 1
    .Parameter = "2"
    .SetFocus
End With

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Parent Property (Office)

 Copy code hover
[image]

CommandBarPopup.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CommandBarPopup object. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Parent

expression A variable that represents a CommandBarPopup object.

Return Value

CommandBar

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Priority Property (Office)

 Copy code hover
[image]

CommandBarPopup.Priority Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the priority of a CommandBarPopup control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Priority

expression A variable that represents a CommandBarPopup object.

Return Value

Integer

Remarks

A control's priority determines whether the control can be dropped from a docked command bar if the command bar controls can't fit in a single row. Controls that can't fit in a single row drop off command bars from right to left.

Example

The following example sets the descriptive text and priority of a command bar popup.

Copy code Copy code
Dim popControl As CommandBarPopup
Set popControl = Application.CommandBars.FindControl _
(Type:=msoControlPopup, Tag:="Graphics")

With popControl.
            .DescriptionText = "Graphics Selection dialog"
            .Priority = 5
End With

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Tag Property (Office)

 Copy code hover
[image]

CommandBarPopup.Tag Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets information about the CommandBarPopup control, such as data that can be used as an argument in procedures, or information that identifies the control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Tag

expression A variable that represents a CommandBarPopup object.

Return Value

String

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.TooltipText Property (Office)

 Copy code hover
[image]

CommandBarPopup.TooltipText Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the text displayed in a CommandBarPopup's ScreenTip. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .TooltipText

expression A variable that represents a CommandBarPopup object.

Return Value

String

Remarks

By default, the value of the Caption property is used as the ScreenTip.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Top Property (Office)

 Copy code hover
[image]

CommandBarPopup.Top Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the distance (in pixels) from the top edge of the specified CommandBarPopup control to the top edge of the screen. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Top

expression Required. A variable that represents a CommandBarPopup object.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Type Property (Office)

 Copy code hover
[image]

CommandBarPopup.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the type of CommandBarPopup control. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Type

expression Required. A variable that represents a CommandBarPopup object.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Visible Property (Office)

 Copy code hover
[image]

CommandBarPopup.Visible Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the Visible property of the CommandBarPopup control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Visible

expression A variable that represents a CommandBarPopup object.

Return Value

Boolean

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Width Property (Office)

 Copy code hover
[image]

CommandBarPopup.Width Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the width (in pixels) of the specified CommandBarPopup control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Width

expression A variable that represents a CommandBarPopup object.

Return Value

Integer

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup Methods (Office)

 Copy code hover
[image]

CommandBarPopup Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Copy | Copies a command bar popup control to an existing command bar.
Delete | Deletes the CommandBarPopup object from its collection.
Execute | Runs the procedure or built-in command assigned to the specified CommandBarPopup control.
Move | Moves the specified CommandBarPopup control to an existing command bar.
Reset | Resets a built-in CommandBarPopup control to its original function and face.
SetFocus | Moves the keyboard focus to the specified CommandBarPopup control. If the popup is disabled or isn't visible, this method will fail.


CommandBarPopup.Copy Method (Office)

 Copy code hover
[image]

CommandBarPopup.Copy Method (Office)
See also Send feedback

Published: July 09, 2012

Copies a command bar popup control to an existing command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Copy(Bar, Before)

expression A variable that represents a CommandBarPopup object.

Parameters

Name | Required/Optional | Data Type | Description
Bar | Optional | Variant | A CommandBar object that represents the destination command bar. If this argument is omitted, the control is copied to the command bar where the control already exists.
Before | Optional | Variant | A number that indicates the position for the new control on the command bar. The new control will be inserted before the control at this position. If this argument is omitted, the control is copied to the end of the command bar.

Return Value

CommandBarControl

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Delete Method (Office)

 Copy code hover
[image]

CommandBarPopup.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the CommandBarPopup object from its collection.

Syntax

expression .Delete(Temporary)

expression Required. A variable that represents a CommandBarPopup object.

Parameters

Name | Required/Optional | Data Type | Description
Temporary | Optional | Variant | True to delete the control for the current session. The application will display the control again in the next session.

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Execute Method (Office)

 Copy code hover
[image]

CommandBarPopup.Execute Method (Office)
See also Send feedback

Published: July 09, 2012

Runs the procedure or built-in command assigned to the specified CommandBarPopup control.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Execute

expression Required. A variable that represents a CommandBarPopup object.

Example

This Microsoft Excel example creates a command bar and then adds a built-in command bar button control to it. The button executes the Excel AutoSum function. This example uses the Execute method to total the selected range of cells when the command bar appears.

VBA Copy code Copy code
Dim cbrCustBar As CommandBar
Dim ctlAutoSum As CommandBarButton
Set cbrCustBar = CommandBars.Add("Custom")
Set ctlAutoSum = cbrCustBar.Controls _
    .Add(msoControlButton, CommandBars("Standard") _
    .Controls("AutoSum").Id)
cbrCustBar.Visible = True
ctlAutoSum.Execute

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Move Method (Office)

 Copy code hover
[image]

CommandBarPopup.Move Method (Office)
See also Send feedback

Published: July 09, 2012

Moves the specified CommandBarPopup control to an existing command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Move(Bar, Before)

expression Required. A variable that represents a CommandBarPopup object.

Parameters

Name | Required/Optional | Data Type | Description
Bar | Optional | Variant | A Command object that represents the destination command bar for the control. If this argument is omitted, the control is moved to the end of the command bar where the control currently resides.
Before | Optional | Variant | A number that indicates the position for the control. The control is inserted before the control currently occupying this position. If this argument is omitted, the control is inserted on the same command bar.

Example

This example moves the first combo box control on the command bar named Custom to the position before the seventh control on that command bar. The example sets the tag to "Selection box" and assigns the control a low priority so that it will likely be dropped from the command bar if all the controls don't fit in one row.

VBA Copy code Copy code
Set allcontrols = CommandBars("Custom").Controls
For Each ctrl In allControls
    If ctrl.Type = msoControlComboBox Then
        With ctrl
            .Move Before:=7
             .Tag = "Selection box"
             .Priority = 5
         End With
         Exit For
    End If
Next

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.Reset Method (Office)

 Copy code hover
[image]

CommandBarPopup.Reset Method (Office)
See also Send feedback

Published: July 09, 2012

Resets a built-in CommandBarPopup control to its original function and face.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Reset

expression A variable that represents a CommandBarPopup object.

Remarks

Resetting a built-in control restores the actions originally intended for the control and resets each of the control's properties back to its original state.

Example

The following example searches all command bars for a CommandBarPopup object whose tag is "Graphics" and then resets it to its default state.

Copy code Copy code
Set myControl = Application.CommandBars.FindControl _
(Type:=msoControlPopup, Tag:="Graphics")
myControl.Reset

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBarPopup.SetFocus Method (Office)

 Copy code hover
[image]

CommandBarPopup.SetFocus Method (Office)
See also Send feedback

Published: July 09, 2012

Moves the keyboard focus to the specified CommandBarPopup control. If the popup is disabled or isn't visible, this method will fail.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .SetFocus

expression A variable that represents a CommandBarPopup object.

Example

The following example sets a reference to an existing command bar popup and then resets it to its default state.

Copy code Copy code
Dim cbPopup As CommandBarPopup
Set cbPopup = Application.CommandBars.FindControl _
(Type:=msoControlPopup, Tag:="Graphics")
cbPopup.Reset

See also

Concepts

CommandBarPopup Object

Other resources

CommandBarPopup Object Members


CommandBars Object (Office)

 Copy code hover
[image]

CommandBars Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of CommandBar objects that represent the command bars in the container application.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Example

Use the CommandBars property to return the CommandBars collection. The following example displays in the Immediate window both the name and local name of each menu bar and toolbar, and it displays a value that indicates whether the menu bar or toolbar is visible.

Copy code Copy code
For Each cbar in CommandBars
    Debug.Print cbar.Name, cbar.NameLocal, cbar.Visible
Next

Use the Add method to add a new command bar to the collection. The following example creates a custom toolbar named "Custom1" and displays it as a floating toolbar.

Copy code Copy code
Set cbar1 = CommandBars.Add(Name:="Custom1", Position:=msoBarFloating)
cbar1.Visible = True

Use enumName, where index is the name or index number of a command bar, to return a single CommandBar object. The following example docks the toolbar named "Custom1" at the bottom of the application window.

Copy code Copy code
CommandBars("Custom1").Position = msoBarBottom
Note Note

Note Note

You can use the name or index number to specify a menu bar or toolbar in the list of available menu bars and toolbars in the container application. However, you must use the name to specify a menu, shortcut menu, or submenu (all of which are represented by CommandBar objects). If two or more custom menus or submenus have the same name, enumName returns the first one. To ensure that you return the correct menu or submenu, locate the pop-up control that displays that menu. Then apply the CommandBar property to the pop-up control to return the command bar that represents that menu.

See also

Concepts

Object Model Reference

Other resources

CommandBars Object Members


CommandBars Members (Office)

 Copy code hover
[image]

CommandBars Members (Office)
Send feedback

Published: July 09, 2012

A collection of CommandBar objects that represent the command bars in the container application.

Events

Name | Description
OnUpdate | Occurs when any change is made to a command bar.

Methods

Name | Description
Add | Creates a new command bar and adds it to the collection of command bars.
CommitRenderingTransaction | Commits the rendering transaction. Returns Nothing.
ExecuteMso | Executes the control identified by the idMso parameter.
FindControl | Gets a CommandBarControl object that fits a specified criteria.
FindControls | Gets the CommandBarControls collection that fits the specified criteria.
GetEnabledMso | Returns True if the control identified by the idMso parameter is enabled.
GetImageMso | Returns an IPictureDisp object of the control image identified by the idMso parameter scaled to the dimensions specified by width and height.
GetLabelMso | Returns the label of the control identified by the idMso parameter as a String.
GetPressedMso | Returns a value indicating whether the toggleButton control identified by the idMso parameter is pressed.
GetScreentipMso | Returns the screentip of the control identified by the idMso parameter as a String.
GetSupertipMso | Returns the supertip of the control identified by the idMso parameter as a String.
GetVisibleMso | Returns True if the control identified by the idMso parameter is visible.
ReleaseFocus | Releases the user interface focus from all command bars.

Properties

Name | Description
ActionControl | Gets the CommandBarControl object whose OnAction property is set to the running procedure. Read-only.
ActiveMenuBar | Gets a CommandBar object that represents the active menu bar in the container application. Read-only.
AdaptiveMenus | This property checks or unchecks the check box control for the option to show menus in Microsoft Office as full or personalized. Read/write.
Application | Gets an Application object that represents the container application for the CommandBars object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a count of the number of command bars in the host application. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBars object was created. Read-only.
DisableAskAQuestionDropdown | Is True if the Answer Wizard dropdown menu is enabled. Read/write.
DisableCustomize | Is True if toolbar customization is disabled. Read/write.
DisplayFonts | Is True if the font names in the Font box are displayed in their actual fonts. Read/write.
DisplayKeysInTooltips | Is True if shortcut keys are displayed in the ToolTips for each command bar control. Read/write.
DisplayTooltips | Is True if ScreenTips are displayed whenever the user positions the pointer over command bar controls. Read/write.
Item | Gets a CommandBar object from the CommandBars collection. Read-only.
LargeButtons | Is True if the toolbar buttons displayed are larger than normal size. Read/write.
MenuAnimationStyle | Gets or sets a MsoMenuAnimation that represents the way a command bar is animated. Read/write.
Parent | Gets the Parent object for the CommandBars object. Read-only.


CommandBars Properties (Office)

 Copy code hover
[image]

CommandBars Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
ActionControl | Gets the CommandBarControl object whose OnAction property is set to the running procedure. Read-only.
ActiveMenuBar | Gets a CommandBar object that represents the active menu bar in the container application. Read-only.
AdaptiveMenus | This property checks or unchecks the check box control for the option to show menus in Microsoft Office as full or personalized. Read/write.
Application | Gets an Application object that represents the container application for the CommandBars object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a count of the number of command bars in the host application. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CommandBars object was created. Read-only.
DisableAskAQuestionDropdown | Is True if the Answer Wizard dropdown menu is enabled. Read/write.
DisableCustomize | Is True if toolbar customization is disabled. Read/write.
DisplayFonts | Is True if the font names in the Font box are displayed in their actual fonts. Read/write.
DisplayKeysInTooltips | Is True if shortcut keys are displayed in the ToolTips for each command bar control. Read/write.
DisplayTooltips | Is True if ScreenTips are displayed whenever the user positions the pointer over command bar controls. Read/write.
Item | Gets a CommandBar object from the CommandBars collection. Read-only.
LargeButtons | Is True if the toolbar buttons displayed are larger than normal size. Read/write.
MenuAnimationStyle | Gets or sets a MsoMenuAnimation that represents the way a command bar is animated. Read/write.
Parent | Gets the Parent object for the CommandBars object. Read-only.


CommandBars.ActionControl Property (Office)

 Copy code hover
[image]

CommandBars.ActionControl Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the CommandBarControl object whose OnAction property is set to the running procedure. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .ActionControl

expression A variable that represents a CommandBars object.

Example

This example creates a command bar named "Custom", adds three buttons to it, and then uses the ActionControl property and the Tag property to determine which command bar button was last clicked.

Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
Set buttonOne = myBar.Controls.Add(Type:=msoControlButton)
With buttonOne
    .FaceId = 133
    .Tag = "RightArrow"
    .OnAction = "whichButton"
End With
Set buttonTwo = myBar.Controls.Add(Type:=msoControlButton)
With buttonTwo
    .FaceId = 134
    .Tag = "UpArrow"
    .OnAction = "whichButton"
End With
Set buttonThree = myBar.Controls.Add(Type:=msoControlButton)
With buttonThree
    .FaceId = 135
    .Tag = "DownArrow"
    .OnAction = "whichButton"
End With
myBar.Visible = True

The following subroutine responds to the OnAction method and determines which command bar button was last clicked.

Copy code Copy code
Sub whichButton()
Select Case CommandBars.ActionControl.Tag
    Case "RightArrow"
        MsgBox ("Right Arrow button clicked.")
    Case "UpArrow"
        MsgBox ("Up Arrow button clicked.")
    Case "DownArrow"
        MsgBox ("Down Arrow button clicked.")
End Select
End Sub

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.ActiveMenuBar Property (Office)

 Copy code hover
[image]

CommandBars.ActiveMenuBar Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CommandBar object that represents the active menu bar in the container application. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .ActiveMenuBar

expression A variable that represents a CommandBars object.

Example

This example adds a temporary pop-up control named "Custom" to the end of the active menu bar, and adds a control named "Import" to the pop-up control.

Copy code Copy code
Set myMenuBar = CommandBars.ActiveMenuBar
Set newMenu = myMenuBar.Controls.Add(Type:=msoControlPopup, Temporary:=True)
newMenu.Caption = "Custom"
Set ctrl1 = newMenu.CommandBar.Controls _
    .Add(Type:=msoControlButton, Id:=1)
With ctrl1
    .Caption = "Import"
    .TooltipText = "Import"
    .Style = msoButtonCaption
End With

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.AdaptiveMenus Property (Office)

 Copy code hover
[image]

CommandBars.AdaptiveMenus Property (Office)
See also Send feedback

Published: July 09, 2012

This property checks or unchecks the check box control for the option to show menus in Microsoft Office as full or personalized. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .AdaptiveMenus

expression A variable that represents a CommandBars object.

Remarks

Is True if adaptive menus are enabled for all applications in Microsoft Office. Read/write Boolean.

This control is set in any application by doing the following:

  1. On the Tools menu, select Customize.

  2. Select the Options tab.

  3. The Always show full menus option is located in the Personalized Menus and Toolbars section.

Example

This example sets three options for all command bars in Microsoft Office, including custom command bars and the controls on them.

Copy code Copy code
With CommandBars
    .LargeButtons = True
    .DisplayFonts = True
    .AdaptiveMenus = True
End With

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.Application Property (Office)

 Copy code hover
[image]

CommandBars.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the CommandBars object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Application

expression A variable that represents a CommandBars object.

Return Value

Object

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.Count Property (Office)

 Copy code hover
[image]

CommandBars.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a count of the number of command bars in the host application. Read-only.

Syntax

expression .Count

expression An expression that returns a CommandBars object.

Return Value

Integer

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.Creator Property (Office)

 Copy code hover
[image]

CommandBars.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CommandBars object was created. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Creator

expression A variable that represents a CommandBars object.

Return Value

Long

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.DisableAskAQuestionDropdown Property (Office)

 Copy code hover
[image]

CommandBars.DisableAskAQuestionDropdown Property (Office)
See also Send feedback

Published: July 09, 2012

Is True if the Answer Wizard dropdown menu is enabled. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .DisableAskAQuestionDropdown

expression A variable that represents a CommandBars object.

Example

The following example switches the DisableAskAQuestionDropdown property on or off.

Copy code Copy code
Sub ToggleQuestionDropdown()
    With Application.CommandBars
        If .DisableAskAQuestionDropdown =  True Then
            .DisableAskAQuestionDropdown = False
        Else
            .DisableAskAQuestionDropdown = True
        End If
    End With
End Sub

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.DisableCustomize Property (Office)

 Copy code hover
[image]

CommandBars.DisableCustomize Property (Office)
See also Send feedback

Published: July 09, 2012

Is True if toolbar customization is disabled. Read/write.

Syntax

expression .DisableCustomize

expression A variable that represents a CommandBars object.

Example

The following example switches the DisableCustomize property on or off.

Copy code Copy code
Sub ToggleCustomize()
 With Application.CommandBars
 If .DisableCustomize = True Then
 .DisableCustomize = False
 Else
 .DisableCustomize = True
 End If
 End With
End Sub

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.DisplayFonts Property (Office)

 Copy code hover
[image]

CommandBars.DisplayFonts Property (Office)
See also Send feedback

Published: July 09, 2012

Is True if the font names in the Font box are displayed in their actual fonts. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .DisplayFonts

expression A variable that represents a CommandBars object.

Example

This example sets three options for all command bars in Microsoft Office, including custom command bars and the controls on them.

Copy code Copy code
With CommandBars
    .LargeButtons = True
    .DisplayFonts = True
    .AdaptiveMenus = True
End With

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.DisplayKeysInTooltips Property (Office)

 Copy code hover
[image]

CommandBars.DisplayKeysInTooltips Property (Office)
See also Send feedback

Published: July 09, 2012

Is True if shortcut keys are displayed in the ToolTips for each command bar control. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .DisplayKeysInTooltips

expression A variable that represents a CommandBars object.

Remarks

To display shortcut keys in ToolTips, you must also set the DisplayTooltips property to True.

Example

This example sets options for all command bars in Microsoft Office.

Copy code Copy code
With CommandBars
    .LargeButtons = True
    .DisplayTooltips = True
    .DisplayKeysInTooltips = True
    .MenuAnimationStyle = msoMenuAnimationUnfold
End With

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.DisplayTooltips Property (Office)

 Copy code hover
[image]

CommandBars.DisplayTooltips Property (Office)
See also Send feedback

Published: July 09, 2012

Is True if ScreenTips are displayed whenever the user positions the pointer over command bar controls. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .DisplayTooltips

expression A variable that represents a CommandBars object.

Remarks

Setting the DisplayTooltips property in a container application immediately affects every command bar in every running Microsoft Office application, and in every Office application opened after the property is set.

Example

This example displays large controls and ToolTips on all command bars.

Copy code Copy code
Set allBars = CommandBars

allBars.LargeButtons = True
allBars.DisplayTooltips = True

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.Item Property (Office)

 Copy code hover
[image]

CommandBars.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CommandBar object from the CommandBars collection. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Item(Index)

expression Required. A variable that represents a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | The name or index number of the object to be returned.

Example

Item is the default member of the object or collection. The following two statements both assign a CommandBar object to cmdBar.

VBA Copy code Copy code
Set cmdBar = CommandBars.Item("Standard")
Set cmdBar = CommandBars("Standard")

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.LargeButtons Property (Office)

 Copy code hover
[image]

CommandBars.LargeButtons Property (Office)
See also Send feedback

Published: July 09, 2012

Is True if the toolbar buttons displayed are larger than normal size. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .LargeButtons

expression A variable that represents a CommandBars object.

Example

This example switches the display size of toolbar buttons on all command bars.

Copy code Copy code
Set allBars = CommandBars
If allBars.LargeButtons Then
    allBars.LargeButtons = False
Else
    allBars.LargeButtons = True
End If

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.MenuAnimationStyle Property (Office)

 Copy code hover
[image]

CommandBars.MenuAnimationStyle Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a MsoMenuAnimation that represents the way a command bar is animated. Read/write.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .MenuAnimationStyle

expression A variable that represents a CommandBars object.

Example

This example sets options for all command bars in Microsoft Office.

Copy code Copy code
With CommandBars
    .LargeButtons = True
    .DisplayTooltips = True
    .DisplayKeysInTooltips = True
    .MenuAnimationStyle = msoMenuAnimationUnfold
End With

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.Parent Property (Office)

 Copy code hover
[image]

CommandBars.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CommandBars object. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Parent

expression A variable that represents a CommandBars object.

Return Value

Object

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars Methods (Office)

 Copy code hover
[image]

CommandBars Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Creates a new command bar and adds it to the collection of command bars.
CommitRenderingTransaction | Commits the rendering transaction. Returns Nothing.
ExecuteMso | Executes the control identified by the idMso parameter.
FindControl | Gets a CommandBarControl object that fits a specified criteria.
FindControls | Gets the CommandBarControls collection that fits the specified criteria.
GetEnabledMso | Returns True if the control identified by the idMso parameter is enabled.
GetImageMso | Returns an IPictureDisp object of the control image identified by the idMso parameter scaled to the dimensions specified by width and height.
GetLabelMso | Returns the label of the control identified by the idMso parameter as a String.
GetPressedMso | Returns a value indicating whether the toggleButton control identified by the idMso parameter is pressed.
GetScreentipMso | Returns the screentip of the control identified by the idMso parameter as a String.
GetSupertipMso | Returns the supertip of the control identified by the idMso parameter as a String.
GetVisibleMso | Returns True if the control identified by the idMso parameter is visible.
ReleaseFocus | Releases the user interface focus from all command bars.


CommandBars.Add Method (Office)

 Copy code hover
[image]

CommandBars.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Creates a new command bar and adds it to the collection of command bars.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .Add(Name, Position, MenuBar, Temporary)

expression Required. A variable that represents a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
Name | Optional | Variant | The name of the new command bar. If this argument is omitted, a default name is assigned to the command bar (such as Custom 1).
Position | Optional | Variant | The position or type of the new command bar. Can be one of the MsoBarPosition constants.
MenuBar | Optional | Variant | True to replace the active menu bar with the new command bar. The default value is False.
Temporary | Optional | Variant | True to make the new command bar temporary. Command bars are deleted when the container application is closed. The default value is False.

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.CommitRenderingTransaction Method (Office)

 Copy code hover
[image]

CommandBars.CommitRenderingTransaction Method (Office)
See also Send feedback

Published: July 09, 2012

Commits the rendering transaction. Returns Nothing.

Version Information

Version Added: Office 2010

Syntax

expression .CommitRenderingTransaction(hwnd)

expression An expression that returns a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
hwnd | Required | Long | A handle to the window in which to commit the rendering transaction.

Return Value

Nothing

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.ExecuteMso Method (Office)

 Copy code hover
[image]

CommandBars.ExecuteMso Method (Office)
See also Send feedback

Published: July 09, 2012

Executes the control identified by the idMso parameter.

Syntax

expression .ExecuteMso(idMso)

expression An expression that returns a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
idMso | Required | String | Identifier for the control.

Remarks

This method is useful in cases where there is no object model for a particular command. Works on controls that are built-in buttons, toggleButtons and splitButtons. On failure it returns E_InvalidArg for an invalid IdMso, and E_Fail for controls that are not enabled or not visible.

Example

The following sample executes the Copy button.

VBA Copy code Copy code
Application.CommandBars.ExecuteMso("Copy")

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.FindControl Method (Office)

 Copy code hover
[image]

CommandBars.FindControl Method (Office)
See also Send feedback

Published: July 09, 2012

Gets a CommandBarControl object that fits a specified criteria.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .FindControl(Type, Id, Tag, Visible)

expression A variable that represents a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
Type | Optional | Variant | The type of control.
Id | Optional | Variant | The identifier of the control.
Tag | Optional | Variant | The tag value of the control.
Visible | Optional | Variant | True to include only visible command bar controls in the search. The default value is False. Visible command bars include all visible toolbars and any menus that are open at the time the FindControl method is executed.

Return Value

CommandBarControl

Remarks

If the CommandBars collection contains two or more controls that fit the search criteria, FindControl returns the first control that's found. If no control that fits the criteria is found, FindControl returns Nothing.

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.FindControls Method (Office)

 Copy code hover
[image]

CommandBars.FindControls Method (Office)
See also Send feedback

Published: July 09, 2012

Gets the CommandBarControls collection that fits the specified criteria.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .FindControls(Type, Id, Tag, Visible)

expression A variable that represents a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
Type | Optional | Variant | Is one of the MsoControlType constants specfying the type of control.
Id | Optional | Variant | The control's identifier.
Tag | Optional | Variant | The control's tag value.
Visible | Optional | Variant | True to include only visible command bar controls in the search. The default value is False.

Return Value

CommandBarControls

Remarks

If no controls that fits the criteria are found, the FindControls method returns Nothing.

Example

This example uses the FindControls method to return all members of the CommandBars collection that have an ID of 18 and displays (in a message box) the number of controls that meet the search criteria.

Copy code Copy code
Dim myControls As CommandBarControls
Set myControls = CommandBars.FindControls(Type:=msoControlButton, ID:=18)
MsgBox "There are " & myControls.Count & _
    " controls that meet the search criteria."

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.GetEnabledMso Method (Office)

 Copy code hover
[image]

CommandBars.GetEnabledMso Method (Office)
See also Send feedback

Published: July 09, 2012

Returns True if the control identified by the idMso parameter is enabled.

Syntax

expression .GetEnabledMso(idMso)

expression An expression that returns a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
idMso | Required | String | Identifier for the control.

Return Value

Boolean

Example

The following sample returns True if the Bold button is enabled.

VBA Copy code Copy code
Application.CommandBars.GetEnabledMso("Bold")

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.GetImageMso Method (Office)

 Copy code hover
[image]

CommandBars.GetImageMso Method (Office)
See also Send feedback

Published: July 09, 2012

Returns an IPictureDisp object of the control image identified by the idMso parameter scaled to the dimensions specified by width and height.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .GetImageMso(idMso, Width, Height)

expression An expression that returns a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
idMso | Required | String | Identifier for the control.
Width | Required | Integer | The width of the image.
Height | Required | Integer | The height of the image.

Return Value

IPictureDisp

Remarks

The Width and Height parameters must be between 16 and 128.

Example

The following sample returns a 32x32 version of the Paste icon as an IPictureDisp object.

VBA Copy code Copy code
Application.CommandBars.GetImageMso("Paste", 32, 32)

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.GetLabelMso Method (Office)

 Copy code hover
[image]

CommandBars.GetLabelMso Method (Office)
See also Send feedback

Published: July 09, 2012

Returns the label of the control identified by the idMso parameter as a String.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .GetLabelMso(idMso)

expression An expression that returns a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
idMso | Required | String | Identifier for the control.

Return Value

String

Example

The following sample returns the String "Paste".

VBA Copy code Copy code
Application.CommandBars.GetLabelMso("Paste")

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.GetPressedMso Method (Office)

 Copy code hover
[image]

CommandBars.GetPressedMso Method (Office)
See also Send feedback

Published: July 09, 2012

Returns a value indicating whether the toggleButton control identified by the idMso parameter is pressed.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .GetPressedMso(idMso)

expression An expression that returns a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
idMso | Required | String | Identifier for the control.

Return Value

Boolean

Example

The following sample returns True when the Bold button is pressed.

VBA Copy code Copy code
Application.CommandBars.GetPressedMso("Bold")

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.GetScreentipMso Method (Office)

 Copy code hover
[image]

CommandBars.GetScreentipMso Method (Office)
See also Send feedback

Published: July 09, 2012

Returns the screentip of the control identified by the idMso parameter as a String.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .GetScreentipMso(idMso)

expression An expression that returns a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
idMso | Required | String | Identifier for the control.

Return Value

String

Example

The following sample returns the String "Paste".

VBA Copy code Copy code
Application.CommandBars.GetScreentipMso("Paste")

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.GetSupertipMso Method (Office)

 Copy code hover
[image]

CommandBars.GetSupertipMso Method (Office)
See also Send feedback

Published: July 09, 2012

Returns the supertip of the control identified by the idMso parameter as a String.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .GetSupertipMso(idMso)

expression An expression that returns a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
idMso | Required | String | Identifier for the control.

Return Value

String

Example

The following sample returns the String "Cut the selection from the document and put it on the Clipboard."

VBA Copy code Copy code
Application.CommandBars.GetSupertipMso("Cut")

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.GetVisibleMso Method (Office)

 Copy code hover
[image]

CommandBars.GetVisibleMso Method (Office)
See also Send feedback

Published: July 09, 2012

Returns True if the control identified by the idMso parameter is visible.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .GetVisibleMso(idMso)

expression An expression that returns a CommandBars object.

Parameters

Name | Required/Optional | Data Type | Description
idMso | Required | String | Identifier for the control.

Return Value

Boolean

Example

The following sample returns True if the Bold button is visible.

VBA Copy code Copy code
Application.CommandBars.GetVisibleMso("Bold")

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars.ReleaseFocus Method (Office)

 Copy code hover
[image]

CommandBars.ReleaseFocus Method (Office)
See also Send feedback

Published: July 09, 2012

Releases the user interface focus from all command bars.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .ReleaseFocus

expression A variable that represents a CommandBars object.

Example

This example adds three blank buttons to the command bar named Custom and sets the focus to the center button. The example then waits five seconds before releasing the user interface focus from all command bars.

Copy code Copy code
Set myBar = CommandBars _
    .Add(Name:="Custom", Position:=msoBarTop, _
    Temporary:=True)
With myBar
    .Controls.Add Type:=msoControlButton
    .Controls.Add Type:=msoControlButton
    .Controls.Add Type:=msoControlButton
    .Visible = True
End With
Set myControl = CommandBars("Custom").Controls(2)
With myControl
    .SetFocus
End With
PauseTime = 5   ' Set duration.
    Start = Timer   ' Set start time.
    Do While Timer  Start + PauseTime
        DoEvents    ' Yield to other processes.
    Loop
    Finish = Timer
CommandBars.ReleaseFocus

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


CommandBars Events (Office)

 Copy code hover
[image]

CommandBars Events (Office)
Send feedback

Published: July 09, 2012

This object has the following events:

Events

Name | Description
OnUpdate | Occurs when any change is made to a command bar.


CommandBars.OnUpdate Event (Office)

 Copy code hover
[image]

CommandBars.OnUpdate Event (Office)
See also Send feedback

Published: July 09, 2012

Occurs when any change is made to a command bar.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .OnUpdate

expression A variable that represents a CommandBars object.

Remarks

The OnUpdate event is recognized by the CommandBar object and all command bar controls. The event is triggered by any change to a command bar or command bar control or any change to the state of a command bar or command bar control. These changes can occur due to a text or cell selection, for example. Since a large number of OnUpdate events can occur during normal usage, developers should exercise caution when using this event. It is strongly recommended that this event be used primarily for checking that a custom command bar has been added or removed by a COM AddIn.

See also

Concepts

CommandBars Object

Other resources

CommandBars Object Members


ContactCard Object (Office)

 Copy code hover
[image]

ContactCard Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a Microsoft Office contact card.

Version Information

Version Added: Office 2010

Remarks

You can create a new instance of a ContactCard object by calling the Microsoft Outlook NameSpace.CreateContactCard method. Before you attempt to do so, you must log into a Microsoft Outlook session.

See also

Concepts

Object Model Reference

Other resources

ContactCard Object Members


ContactCard Members (Office)

 Copy code hover
[image]

ContactCard Members (Office)
Send feedback

Published: July 09, 2012

Represents a Microsoft Office contact card.

Methods

Name | Description
Close | Closes the contact card.
Show | Displays the contact card at the specified x-coordinate position outside the specified rectangle.

Properties

Name | Description
Application | Returns an Application object that represents the parent Office application for the ContactCard object. Read-only.
Creator | Returns a Long that indicates the application in which the ContactCard object was created. Read-only.


ContactCard Properties (Office)

 Copy code hover
[image]

ContactCard Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Returns an Application object that represents the parent Office application for the ContactCard object. Read-only.
Creator | Returns a Long that indicates the application in which the ContactCard object was created. Read-only.


ContactCard.Application Property (Office)

 Copy code hover
[image]

ContactCard.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Returns an Application object that represents the parent Office application for the ContactCard object. Read-only.

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a ContactCard object.

Return Value

Application

See also

Concepts

ContactCard Object

Other resources

ContactCard Object Members


ContactCard.Creator Property (Office)

 Copy code hover
[image]

ContactCard.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Returns a Long that indicates the application in which the ContactCard object was created. Read-only.

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a ContactCard object.

Return Value

Long

See also

Concepts

ContactCard Object

Other resources

ContactCard Object Members


ContactCard Methods (Office)

 Copy code hover
[image]

ContactCard Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Close | Closes the contact card.
Show | Displays the contact card at the specified x-coordinate position outside the specified rectangle.


ContactCard.Close Method (Office)

 Copy code hover
[image]

ContactCard.Close Method (Office)
See also Send feedback

Published: July 09, 2012

Closes the contact card.

Version Information

Version Added: Office 2010

Syntax

expression .Close

expression An expression that returns a ContactCard object.

Return Value

Nothing

Remarks

You can close a contact card either in the user interface or programmatically by calling the Close method.

See also

Concepts

ContactCard Object

Other resources

ContactCard Object Members


ContactCard.Show Method (Office)

 Copy code hover
[image]

ContactCard.Show Method (Office)
See also Send feedback

Published: July 09, 2012

Displays the contact card at the specified x-coordinate position outside the specified rectangle.

Version Information

Version Added: Office 2010

Syntax

expression .Show(Style, Left, Right, Top, Bottom, xcord, fDelay)

expression An expression that returns a ContactCard object.

Parameters

Name | Required/Optional | Data Type | Description
Style | Required | MsoContactCardStyle | Determines whether the card is displayed as a hover card or as a fully expanded card. See Remarks for possible values.
Left | Required | Long | Specifies the x-coordinate of the left side of the rectangle where the card is not displayed.
Right | Required | Long | Specifies the x-coordinate of the right side of the rectangle where the card is not displayed.
Top | Required | Long | Specifies the y-coordinate of the top side of the rectangle where the card is not displayed.
Bottom | Required | Long | Specifies the y-coordinate of the bottom side of the rectangle where the card is not displayed.
xcord | Required | Long | Specifies the x-coordinate position of the left edge of the card.
fDelay | Required | Boolean | Determines if there is a delay before the card is displayed.

Return Value

Nothing

Remarks

Style must be one of the following MsoContactCardStyle values.

Constant | Value | Description
msoContactCardTypeEnterpriseContact | 0 | Represents a contact card for an enterprise contact address.
msoContactCardTypePersonalContact | 1 | Represents a contact card for a personal contact address.
msoContactCardTypeUnknownContact | 2 | Represents a contact card for an unknown contact address.
msoContactCardTypeEnterpriseGroup | 3 | Represents a contact card for an enterprise distribution list contact address.
msoContactCardTypePersonalDistributionList | 4 | Represents a contact card for a personal distribution list contact address.

fDelay applies only if Style is msoContactCardStyleHover. For all other card styles, fDelay is ignored.

See also

Concepts

ContactCard Object

Other resources

ContactCard Object Members


Crop Object (Office)

 Copy code hover
[image]

Crop Object (Office)
See also Send feedback

Published: July 09, 2012

An object used to remove a portion of an image.

Version Information

Version Added: Office 2010

Example

The following example inserts a 200 x 200 image into a PowerPoint presentation approximately in the center of the slide. It then resizes the image inside the frame to 100 x 100. The image frame stays at 200 x 200. The code then adds a square (the default shape) just above and to the right of the image, essentially cropping the lower left corner of the image.

VBA Copy code Copy code
Sub CropImage()
 ActivePresentation.Slides(1).Shapes.AddPicture "c:\myImage.png", msoFalse, msoTrue, 250,150, 200, 200
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetX = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetY = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeLeft = 330
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeTop = 170
End Sub

See also

Concepts

Object Model Reference

Other resources

Crop Object Members


Crop Members (Office)

 Copy code hover
[image]

Crop Members (Office)
Send feedback

Published: July 09, 2012

An object used to remove a portion of an image.

Properties

Name | Description
Application | Gets the Application object of the host application. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the Crop object was created. Read-only.
PictureHeight | Gets or sets the height of the image that is to be cropped. Read/write.
PictureOffsetX | Gets or sets the x-axis offset of the image that is to be cropped. Read/write.
PictureOffsetY | Gets or sets the y-axis offset of the image that is to be cropped. Read/write.
PictureWidth | Gets or sets the width of the image that is to be cropped. Read/write
ShapeHeight | Gets or sets the height of a shape that is used to crop an image. Read/write
ShapeLeft | Gets or sets the location of the left-side of a shape that is used to crop an image. Read/write.
ShapeTop | Gets or sets the location of the top of a shape that is used to crop an image. Read/write.
ShapeWidth | Gets or sets the width of a shape that is used to crop an image. Read/write


Crop Properties (Office)

 Copy code hover
[image]

Crop Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets the Application object of the host application. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the Crop object was created. Read-only.
PictureHeight | Gets or sets the height of the image that is to be cropped. Read/write.
PictureOffsetX | Gets or sets the x-axis offset of the image that is to be cropped. Read/write.
PictureOffsetY | Gets or sets the y-axis offset of the image that is to be cropped. Read/write.
PictureWidth | Gets or sets the width of the image that is to be cropped. Read/write
ShapeHeight | Gets or sets the height of a shape that is used to crop an image. Read/write
ShapeLeft | Gets or sets the location of the left-side of a shape that is used to crop an image. Read/write.
ShapeTop | Gets or sets the location of the top of a shape that is used to crop an image. Read/write.
ShapeWidth | Gets or sets the width of a shape that is used to crop an image. Read/write


Crop.Application Property (Office)

 Copy code hover
[image]

Crop.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Application object of the host application. Read-only.

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a Crop object.

Return Value

Object

See also

Concepts

Crop Object

Other resources

Crop Object Members


Crop.Creator Property (Office)

 Copy code hover
[image]

Crop.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the Crop object was created. Read-only.

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a Crop object.

Return Value

Long

See also

Concepts

Crop Object

Other resources

Crop Object Members


Crop.PictureHeight Property (Office)

 Copy code hover
[image]

Crop.PictureHeight Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the height of the image that is to be cropped. Read/write.

Version Information

Version Added: Office 2010

Syntax

expression .PictureHeight

expression An expression that returns a Crop object.

Return Value

Single

Example

The following example inserts a 200 x 200 image into a PowerPoint presentation approximately in the center of the slide. It then resizes the image inside the frame to 100 x 100. The image frame stays at 200 x 200. The code then adds a square (the default shape) just above and to the right of the image, essentially cropping the lower left corner of the image.

VBA Copy code Copy code
Sub CropImage()
 ActivePresentation.Slides(1).Shapes.AddPicture "c:\myImage.png", msoFalse, msoTrue, 250,150, 200, 200
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetX = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetY = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeLeft = 330
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeTop = 170
End Sub

See also

Concepts

Crop Object

Other resources

Crop Object Members


Crop.PictureOffsetX Property (Office)

 Copy code hover
[image]

Crop.PictureOffsetX Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the x-axis offset of the image that is to be cropped. Read/write.

Version Information

Version Added: Office 2010

Syntax

expression .PictureOffsetX

expression An expression that returns a Crop object.

Return Value

Single

Remarks

OffsetX and OffsetY are relative to center of the shape and image.

Example

The following example inserts a 200 x 200 image into a PowerPoint presentation approximately in the center of the slide. It then resizes the image inside the frame to 100 x 100. The image frame stays at 200 x 200. The code then adds a square (the default shape) just above and to the right of the image, essentially cropping the lower left corner of the image.

VBA Copy code Copy code
Sub CropImage()
 ActivePresentation.Slides(1).Shapes.AddPicture "c:\myImage.png", msoFalse, msoTrue, 250,150, 200, 200
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetX = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetY = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeLeft = 330
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeTop = 170
End Sub

See also

Concepts

Crop Object

Other resources

Crop Object Members


Crop.PictureOffsetY Property (Office)

 Copy code hover
[image]

Crop.PictureOffsetY Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the y-axis offset of the image that is to be cropped. Read/write.

Version Information

Version Added: Office 2010

Syntax

expression .PictureOffsetY

expression An expression that returns a Crop object.

Return Value

Single

Remarks

OffsetX and OffsetY are relative to center of the shape and image.

Example

The following example inserts a 200 x 200 image into a PowerPoint presentation approximately in the center of the slide. It then resizes the image inside the frame to 100 x 100. The image frame stays at 200 x 200. The code then adds a square (the default shape) just above and to the right of the image, essentially cropping the lower left corner of the image.

VBA Copy code Copy code
Sub CropImage()
 ActivePresentation.Slides(1).Shapes.AddPicture "c:\myImage.png", msoFalse, msoTrue, 250,150, 200, 200
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetX = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetY = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeLeft = 330
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeTop = 170
End Sub

See also

Concepts

Crop Object

Other resources

Crop Object Members


Crop.PictureWidth Property (Office)

 Copy code hover
[image]

Crop.PictureWidth Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the width of the image that is to be cropped. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .PictureWidth

expression An expression that returns a Crop object.

Return Value

Single

Example

The following example inserts a 200 x 200 image into a PowerPoint presentation approximately in the center of the slide. It then resizes the image inside the frame to 100 x 100. The image frame stays at 200 x 200. The code then adds a square (the default shape) just above and to the right of the image, essentially cropping the lower left corner of the image.

VBA Copy code Copy code
Sub CropImage()
 ActivePresentation.Slides(1).Shapes.AddPicture "c:\myImage.png", msoFalse, msoTrue, 250,150, 200, 200
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetX = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetY = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeLeft = 330
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeTop = 170
End Sub

See also

Concepts

Crop Object

Other resources

Crop Object Members


Crop.ShapeHeight Property (Office)

 Copy code hover
[image]

Crop.ShapeHeight Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the height of a shape that is used to crop an image. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .ShapeHeight

expression An expression that returns a Crop object.

Return Value

Single

Example

The following example inserts a 200 x 200 image into a PowerPoint presentation approximately in the center of the slide. It then resizes the image inside the frame to 100 x 100. The image frame stays at 200 x 200. The code then adds a square (the default shape) just above and to the right of the image, essentially cropping the lower left corner of the image.

VBA Copy code Copy code
Sub CropImage()
 ActivePresentation.Slides(1).Shapes.AddPicture "c:\myImage.png", msoFalse, msoTrue, 250,150, 200, 200
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetX = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetY = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeLeft = 330
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeTop = 170
End Sub

See also

Concepts

Crop Object

Other resources

Crop Object Members


Crop.ShapeLeft Property (Office)

 Copy code hover
[image]

Crop.ShapeLeft Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the location of the left-side of a shape that is used to crop an image. Read/write.

Version Information

Version Added: Office 2010

Syntax

expression .ShapeLeft

expression An expression that returns a Crop object.

Return Value

Single

Remarks

In Microsoft Word, the ShapeLeft and ShapeTop properties will return an error is the picture or shape have the wrap text set to Inline with Text.

Example

The following example inserts a 200 x 200 image into a PowerPoint presentation approximately in the center of the slide. It then resizes the image inside the frame to 100 x 100. The image frame stays at 200 x 200. The code then adds a square (the default shape) just above and to the right of the image, essentially cropping the lower left corner of the image.

VBA Copy code Copy code
Sub CropImage()
 ActivePresentation.Slides(1).Shapes.AddPicture "c:\myImage.png", msoFalse, msoTrue, 250,150, 200, 200
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetX = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetY = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeLeft = 330
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeTop = 170
End Sub

See also

Concepts

Crop Object

Other resources

Crop Object Members


Crop.ShapeTop Property (Office)

 Copy code hover
[image]

Crop.ShapeTop Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the location of the top of a shape that is used to crop an image. Read/write.

Version Information

Version Added: Office 2010

Syntax

expression .ShapeTop

expression An expression that returns a Crop object.

Return Value

Single

Remarks

In Microsoft Word, the ShapeLeft and ShapeTop properties will return an error is the picture or shape have the wrap text set to Inline with Text.

Example

The following example inserts a 200 x 200 image into a PowerPoint presentation approximately in the center of the slide. It then resizes the image inside the frame to 100 x 100. The image frame stays at 200 x 200. The code then adds a square (the default shape) just above and to the right of the image, essentially cropping the lower left corner of the image.

VBA Copy code Copy code
Sub CropImage()
 ActivePresentation.Slides(1).Shapes.AddPicture "c:\myImage.png", msoFalse, msoTrue, 250,150, 200, 200
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetX = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetY = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeLeft = 330
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeTop = 170
End Sub

See also

Concepts

Crop Object

Other resources

Crop Object Members


Crop.ShapeWidth Property (Office)

 Copy code hover
[image]

Crop.ShapeWidth Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the width of a shape that is used to crop an image. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .ShapeWidth

expression An expression that returns a Crop object.

Return Value

Single

Example

The following example inserts a 200 x 200 image into a PowerPoint presentation approximately in the center of the slide. It then resizes the image inside the frame to 100 x 100. The image frame stays at 200 x 200. The code then adds a square (the default shape) just above and to the right of the image, essentially cropping the lower left corner of the image.

VBA Copy code Copy code
Sub CropImage()
 ActivePresentation.Slides(1).Shapes.AddPicture "c:\myImage.png", msoFalse, msoTrue, 250,150, 200, 200
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetX = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.PictureOffsetY = 0
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeHeight = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeWidth = 100
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeLeft = 330
 ActivePresentation.Slides(1).Shapes(1).PictureFormat.Crop.ShapeTop = 170
End Sub

See also

Concepts

Crop Object

Other resources

Crop Object Members


CustomTaskPane Object (Office)

 Copy code hover
[image]

CustomTaskPane Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a custom task pane in the container application.

Example

The following example, written in C#, creates an instance of a CustomTaskPane object and implements its only method, CTPFactoryAvailable. CTPFactoryAvailable passes an ICTPFactory object to the add-in, which you can use during the add-in's lifetime to create a task pane by using the CreateCTP method. Note that the example assumes that the task pane is part of an COM add-in and thus implements Extensibility.IDTExtensibility2. The add-in also references a Microsoft ActiveX® control, SampleActiveX.myControl, that was created in a separate project.

Copy code Copy code
public class Connect : Object, Extensibility.IDTExtensibility2, ICustomTaskPaneConsumer
...
object missing = Type.Missing;
public CustomTaskPane CTP = null;

public void CTPFactoryAvailable(ICTPFactory CTPFactoryInst)
{
 CTP = CTPFactoryInst.CreateCTP("SampleActiveX.myControl", "Task Pane Example", missing);
 sampleAX = (myControl)CTP.ContentControl;
 sampleAX.InsertTextClicked += new InsertTextEventHandler(sampleAX_InsertTextClicked);
 CTP.Visible = true;
}
...
Note Note

You can create custom task panes in any language that supports COM and allows you to create dynamic-linked library (DLL) files. For example, Microsoft Visual Basic® 6.0, Microsoft Visual Basic .NET, Microsoft Visual C++®, Microsoft Visual C++ .NET, and Microsoft Visual C#®. However, Microsoft Visual Basic for Applications (VBA) does not support creating custom task panes.

See also

Concepts

Object Model Reference

Other resources

CustomTaskPane Object Members


CustomTaskPane Members (Office)

 Copy code hover
[image]

CustomTaskPane Members (Office)
Send feedback

Published: July 09, 2012

Represents a custom task pane in the container application.

Events

Name | Description
DockPositionStateChange | Occurs when the user changes the docking position of the active custom task pane.
VisibleStateChange | Occurs when the user changes the visibility of the custom task pane.

Methods

Name | Description
Delete | Deletes the active custom task pane.

Properties

Name | Description
Application | Gets the Application object of the host application. Read-only.
ContentControl | Gets the Microsoft ActiveX® control instance displayed in the custom task pane frame. Read-only.
DockPosition | Gets or sets an enumerated value specifying the docked position of a CustomTaskPane object. Read/write.
DockPositionRestrict | Gets or sets an enumerated value specifying a restriction on the orientation of a CustomTaskPane object. Read/write.
Height | Gets or sets the height of the CustomTaskPane object (in points). Read/write.
Title | Gets a String representing the title of a CustomTaskPane object. Read-only.
Visible | True if the specified CustomTaskPane object is visible. Read/write.
Width | Gets or sets the width of the task pane specified by the CustomTaskPane object. Read/write.
Window | Gets the parent window object of the CustomTaskPane object. Read-only.


CustomTaskPane Properties (Office)

 Copy code hover
[image]

CustomTaskPane Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets the Application object of the host application. Read-only.
ContentControl | Gets the Microsoft ActiveX® control instance displayed in the custom task pane frame. Read-only.
DockPosition | Gets or sets an enumerated value specifying the docked position of a CustomTaskPane object. Read/write.
DockPositionRestrict | Gets or sets an enumerated value specifying a restriction on the orientation of a CustomTaskPane object. Read/write.
Height | Gets or sets the height of the CustomTaskPane object (in points). Read/write.
Title | Gets a String representing the title of a CustomTaskPane object. Read-only.
Visible | True if the specified CustomTaskPane object is visible. Read/write.
Width | Gets or sets the width of the task pane specified by the CustomTaskPane object. Read/write.
Window | Gets the parent window object of the CustomTaskPane object. Read-only.


CustomTaskPane.Application Property (Office)

 Copy code hover
[image]

CustomTaskPane.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Application object of the host application. Read-only.

Syntax

expression .Application

expression An expression that returns a CustomTaskPane object.

Return Value

Object

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomTaskPane.ContentControl Property (Office)

 Copy code hover
[image]

CustomTaskPane.ContentControl Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Microsoft ActiveX® control instance displayed in the custom task pane frame. Read-only.

Syntax

expression .ContentControl

expression An expression that returns a CustomTaskPane object.

Return Value

Object

Remarks

This property is set once at creation.

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomTaskPane.DockPosition Property (Office)

 Copy code hover
[image]

CustomTaskPane.DockPosition Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets an enumerated value specifying the docked position of a CustomTaskPane object. Read/write.

Syntax

expression .DockPosition

expression An expression that returns a CustomTaskPane object.

Return Value

MsoCTPDockPosition

Remarks

Defaults to Right for Right-to-Left languages and Left for Left-toRight languages.

The value of this property can be set to one of the following MsoCTPDockPosition constants.

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomTaskPane.DockPositionRestrict Property (Office)

 Copy code hover
[image]

CustomTaskPane.DockPositionRestrict Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets an enumerated value specifying a restriction on the orientation of a CustomTaskPane object. Read/write.

Syntax

expression .DockPositionRestrict

expression An expression that returns a CustomTaskPane object.

Return Value

MsoCTPDockPositionRestrict

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomTaskPane.Height Property (Office)

 Copy code hover
[image]

CustomTaskPane.Height Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the height of the CustomTaskPane object (in points). Read/write.

Syntax

expression .Height

expression An expression that returns a CustomTaskPane object.

Return Value

Integer

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomTaskPane.Title Property (Office)

 Copy code hover
[image]

CustomTaskPane.Title Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a String representing the title of a CustomTaskPane object. Read-only.

Syntax

expression .Title

expression An expression that returns a CustomTaskPane object.

Return Value

String

Remarks

This property is set once at creation.

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomTaskPane.Visible Property (Office)

 Copy code hover
[image]

CustomTaskPane.Visible Property (Office)
See also Send feedback

Published: July 09, 2012

True if the specified CustomTaskPane object is visible. Read/write.

Syntax

expression .Visible

expression An expression that returns a CustomTaskPane object.

Return Value

Boolean

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomTaskPane.Width Property (Office)

 Copy code hover
[image]

CustomTaskPane.Width Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the width of the task pane specified by the CustomTaskPane object. Read/write.

Syntax

expression .Width

expression An expression that returns a CustomTaskPane object.

Return Value

Integer

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomTaskPane.Window Property (Office)

 Copy code hover
[image]

CustomTaskPane.Window Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the parent window object of the CustomTaskPane object. Read-only.

Syntax

expression .Window

expression An expression that returns a CustomTaskPane object.

Return Value

Object

Remarks

The specific class for this property depends on the host application.

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomTaskPane Methods (Office)

 Copy code hover
[image]

CustomTaskPane Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes the active custom task pane.


CustomTaskPane.Delete Method (Office)

 Copy code hover
[image]

CustomTaskPane.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the active custom task pane.

Syntax

expression .Delete

expression An expression that returns a CustomTaskPane object.

Example

The following example, written in C#, creates an instance of a CustomTaskPane object and implements its only method, CTPFactoryAvailable. CTPFactoryAvailable passes a CTPFactory object to the add-in, that can be used during the add-in's lifetime to create task panes by using the CreateCTP method. The project also implements a button that is used to delete the active task pane. Note that the example assumes that the task pane is part of an COM add-in and thus implements Extensibility.IDTExtensibility2. The add-in also refers to a Microsoft ActiveX® control, SampleActiveX.myControl, that was created in a separate project.

Copy code Copy code
public class Connect : Object, Extensibility.IDTExtensibility2, ICustomTaskPaneConsumer
...
object missing = Type.Missing;
public CustomTaskPane CTP = null;

public void CTPFactoryAvailable(ICTPFactory CTPFactoryInst)
{
 CTP = CTPFactoryInst.CreateCTP("SampleActiveX.myControl", "Task Pane Example", missing);
 sampleAX = (myControl)CTP.ContentControl;
 sampleAX.InsertTextClicked += new InsertTextEventHandler(sampleAX_InsertTextClicked);
 CTP.Visible = true;
}
...
Note Note

You can create custom task panes in any language that supports COM and allows you to create dynamic-linked library (DLL) files. For example, Microsoft Visual Basic® 6.0, Microsoft Visual Basic .NET, Microsoft Visual C++®, Microsoft Visual C++ .NET, and Microsoft Visual C#®. However, Microsoft Visual Basic for Applications (VBA) does not support creating custom task panes.

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomTaskPane Events (Office)

 Copy code hover
[image]

CustomTaskPane Events (Office)
Send feedback

Published: July 09, 2012

This object has the following events:

Events

Name | Description
DockPositionStateChange | Occurs when the user changes the docking position of the active custom task pane.
VisibleStateChange | Occurs when the user changes the visibility of the custom task pane.


CustomTaskPane.DockPositionStateChange Event (Office)

 Copy code hover
[image]

CustomTaskPane.DockPositionStateChange Event (Office)
See also Send feedback

Published: July 09, 2012

Occurs when the user changes the docking position of the active custom task pane.

Syntax

expression .DockPositionStateChange(CustomTaskPaneInst, )

expression An expression that returns a CustomTaskPane object.

Parameters

Name | Required/Optional | Data Type | Description
CustomTaskPaneInst | Required | Object | The active custom task pane.

Example

The following example, written in C#, creates a custom task pane and adds a Microsoft ActiveX® button control that was created in another project. A DockPositionStateChange event of type _CustomTaskPaneEvents_DockPositionStateChangeEventHandler is then defined. When the event is triggered, a message box is displayed telling the user that the docked task pane has been moved.

Copy code Copy code
object missing = Type.Missing;
public CustomTaskPane CTP = null;

public void CTPFactoryAvailable(ICTPFactory CTPFactoryInst)
{
 CTP = CTPFactoryInst.CreateCTP("SampleActiveX.myControl", "Task Pane Example", missing);
 sampleAX = (myControl)CTP.ContentControl;
 sampleAX.InsertTextClicked += new InsertTextEventHandler(sampleAX_InsertTextClicked);
 CTP.Visible = true;

 CTP.DockPositionStateChange += new _CustomTaskPaneEvents_DockPositionStateChangeEventHandler(CTP_DockPositionStateChange);

}

private void CTP_DockPositionStateChange(object sender, string dockpositionArgs)
{
 Console.WriteLine("The custom task pane was moved");
}
Note Note

Custom task panes can be created in any language that supports COM and allows you to create dynamic-linked library (DLL) files. For example, Microsoft Visual Basic® 6.0, Microsoft Visual Basic .NET, Microsoft Visual C++®, Microsoft Visual C++ .NET, and Microsoft Visual C#®. However, Microsoft Visual Basic for Applications (VBA) does not support creating custom task panes.

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomTaskPane.VisibleStateChange Event (Office)

 Copy code hover
[image]

CustomTaskPane.VisibleStateChange Event (Office)
See also Send feedback

Published: July 09, 2012

Occurs when the user changes the visibility of the custom task pane.

Syntax

expression .VisibleStateChange(CustomTaskPaneInst, )

expression An expression that returns a CustomTaskPane object.

Parameters

Name | Required/Optional | Data Type | Description
CustomTaskPaneInst | Required | CustomTaskPane | The active task pane.

Example

The following example, written in C#, creates a custom task pane and adds an ActiveX button control created in another project. A VisibleStateChange event of type _CustomTaskPaneEvents_VisibleStateChangeEventHandler is defined in the procedure. When the event is triggered, the event handler displays a message box depending on whether the task pane is currently visible or hidden.

Copy code Copy code
object missing = Type.Missing;
public CustomTaskPane CTP = null;

public void CTPFactoryAvailable(ICTPFactory CTPFactoryInst)
{
 CTP = CTPFactoryInst.CreateCTP("SampleActiveX.myControl", "Task Pane Example", missing);
 sampleAX = (myControl)CTP.ContentControl;
 sampleAX.InsertTextClicked += new InsertTextEventHandler(sampleAX_InsertTextClicked);
 CTP.Visible = true;

 CTP.VisibleStateChange += new _CustomTaskPaneEvents_VisibleStateChangeEventHandler(CTP_VisibleStateChange);
}

private void CTP_VisibleStateChange(object sender, string visiblestateArgs)
{
 if (CTP.Visible)
 {
 Console.WriteLine("The custom task pane is now visible");
 }
 else
 {
 Console.WriteLine("The custom task pane has been hidden");
 }
}
Note Note

Custom task panes can be created in any language that supports COM and allows you to create dynamic-linked library (DLL) files. For example, Microsoft Visual Basic® 6.0, Microsoft Visual Basic .NET, Microsoft Visual C++®, Microsoft Visual C++ .NET, and Microsoft Visual C#®. However, Microsoft Visual Basic for Applications (VBA) does not support creating custom task panes.

See also

Concepts

CustomTaskPane Object

Other resources

CustomTaskPane Object Members


CustomXMLNode Object (Office)

 Copy code hover
[image]

CustomXMLNode Object (Office)
See also Send feedback

Published: July 09, 2012

Represents an XML node in a tree in a document. The CustomXMLNode object is a member of the CustomXMLNodes collection.

Remarks

The CustomXMLNode object is designed to have functional parity with the IXMLDOMNode interface. In addition, it contains an XPath property, which is a great improvement over the objects provided by MSXML.

Example

The following example selects a single node from a CustomXMLPart object by using an XPath expression and assigns it to a CustomXMLNode object.

VBA Copy code Copy code
Sub CustomXmlNodes()
    Dim cxp1 As CustomXMLPart
    Dim cxn As CustomXMLNode

    With ActiveDocument

        ' Returns the first custom xml part with the given root namespace.
        Set cxp1 = .CustomXMLParts("urn:invoice:namespace")

        ' Get the first node matching the XPath expression.
        Set cxn = cxp1.SelectSingleNode("//*[@quantity < 4]")

    End With

End Sub

See also

Concepts

Object Model Reference

Other resources

CustomXMLNode Object Members


CustomXMLNode Members (Office)

 Copy code hover
[image]

CustomXMLNode Members (Office)
Send feedback

Published: July 09, 2012

Represents an XML node in a tree in a document. The CustomXMLNode object is a member of the CustomXMLNodes collection.

Methods

Name | Description
AppendChildNode | Appends a single node as the last child under the context element node in the tree.
AppendChildSubtree | Adds a subtree as the last child under the context element node in the tree.
Delete | Deletes the current node from the tree (including all of its children, if any exist).
HasChildNodes | Gets True if the current element node has child element nodes.
InsertNodeBefore | Inserts a new node just before the context node in the tree.
InsertSubtreeBefore | Inserts the specified subtree into the location just before the context node.
RemoveChild | Removes the specified child node from the tree.
ReplaceChildNode | Removes the specified child node (and its subtree) from the main tree, and replaces it with a different node in the same location.
ReplaceChildSubtree | Removes the specified node (and its subtree) from the main tree, and replaces it with a different subtree in the same location.
SelectNodes | Selects a collection of nodes matching an XPath expression. This method differs from the CustomXMLPart.SelectNodes method in that the XPath expression will be evaluated starting with the 'expression' node as the context node.
SelectSingleNode | Selects a single node from a collection matching an XPath expression. This method differs from the CustomXMLPart.SelectSingleNode method in that the XPath expression will be evaluated starting with the 'expression' node as the context node.

Properties

Name | Description
Application | Gets an Application object that represents the container application for a CustomXMLNode. Read-only.
Attributes | Gets a CustomXMLNodes collection representing the attributes of the current element in the current node. Read-only.
BaseName | Gets the base name of the node without the namespace prefix, if one exists, in the Document Object Model (DOM). Read-only.
ChildNodes | Gets a CustomXMLNodes collection containing all of the child elements of the current node. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLNode object was created. Read-only.
FirstChild | Gets a CustomXMLNode object corresponding to the first child element of the current node. If the node has no child elements (or if it isn't of type msoCustomXMLNodeElement), returns Nothing. Read-only.
LastChild | Gets a CustomXMLNode object corresponding to the last child element of the current node. If the node has no child elements (or if it is not of type msoCustomXMLNodeElement), the property returns Nothing. Read-only.
NamespaceURI | Gets the unique address identifier for the namespace of the CustomXMLNode object. Read-only.
NextSibling | Gets the next sibling node (element, comment, or processing instruction) of the current node. If the node is the last sibling at its level, the property returns Nothing. Read-only.
NodeType | Gets the type of the current node. Read-only.
NodeValue | Gets or sets the value of the current node. Read/write.
OwnerDocument | Gets the object representing the Microsoft Excel workbook, Microsoft PowerPoint presentation, or the Microsoft Word document associated with this node. Read-only.
OwnerPart | Gets the object representing the part associated with this node. Read-only.
Parent | Gets the Parent object for the CustomXMLNode object. Read-only.
ParentNode | Gets the parent element node of the current node. If the current node is at the root level, the property returns Nothing. Read-only.
PreviousSibling | Gets the previous sibling node (element, comment, or processing instruction) of the current node. If the current node is the first sibling at its level, the property returns Nothing. Read-only.
Text | Gets or sets the text for the current node. Read/write.
XML | Gets the XML representation of the current node and its children, if any exist. Read-only.
XPath | Gets a String with the canonicalized XPath for the current node. If the node is no longer in the Document Object Model (DOM), the property returns an error message. Read-only.


CustomXMLNode Properties (Office)

 Copy code hover
[image]

CustomXMLNode Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for a CustomXMLNode. Read-only.
Attributes | Gets a CustomXMLNodes collection representing the attributes of the current element in the current node. Read-only.
BaseName | Gets the base name of the node without the namespace prefix, if one exists, in the Document Object Model (DOM). Read-only.
ChildNodes | Gets a CustomXMLNodes collection containing all of the child elements of the current node. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLNode object was created. Read-only.
FirstChild | Gets a CustomXMLNode object corresponding to the first child element of the current node. If the node has no child elements (or if it isn't of type msoCustomXMLNodeElement), returns Nothing. Read-only.
LastChild | Gets a CustomXMLNode object corresponding to the last child element of the current node. If the node has no child elements (or if it is not of type msoCustomXMLNodeElement), the property returns Nothing. Read-only.
NamespaceURI | Gets the unique address identifier for the namespace of the CustomXMLNode object. Read-only.
NextSibling | Gets the next sibling node (element, comment, or processing instruction) of the current node. If the node is the last sibling at its level, the property returns Nothing. Read-only.
NodeType | Gets the type of the current node. Read-only.
NodeValue | Gets or sets the value of the current node. Read/write.
OwnerDocument | Gets the object representing the Microsoft Excel workbook, Microsoft PowerPoint presentation, or the Microsoft Word document associated with this node. Read-only.
OwnerPart | Gets the object representing the part associated with this node. Read-only.
Parent | Gets the Parent object for the CustomXMLNode object. Read-only.
ParentNode | Gets the parent element node of the current node. If the current node is at the root level, the property returns Nothing. Read-only.
PreviousSibling | Gets the previous sibling node (element, comment, or processing instruction) of the current node. If the current node is the first sibling at its level, the property returns Nothing. Read-only.
Text | Gets or sets the text for the current node. Read/write.
XML | Gets the XML representation of the current node and its children, if any exist. Read-only.
XPath | Gets a String with the canonicalized XPath for the current node. If the node is no longer in the Document Object Model (DOM), the property returns an error message. Read-only.


CustomXMLNode.Application Property (Office)

 Copy code hover
[image]

CustomXMLNode.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for a CustomXMLNode. Read-only.

Syntax

expression .Application

expression An expression that returns a CustomXMLNode object.

Return Value

Object

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.Attributes Property (Office)

 Copy code hover
[image]

CustomXMLNode.Attributes Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CustomXMLNodes collection representing the attributes of the current element in the current node. Read-only.

Syntax

expression .Attributes

expression An expression that returns a CustomXMLNode object.

Return Value

CustomXMLNodes

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.BaseName Property (Office)

 Copy code hover
[image]

CustomXMLNode.BaseName Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the base name of the node without the namespace prefix, if one exists, in the Document Object Model (DOM). Read-only.

Syntax

expression .BaseName

expression An expression that returns a CustomXMLNode object.

Return Value

String

Remarks

This is the default member of CustomXMLNode object.

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.ChildNodes Property (Office)

 Copy code hover
[image]

CustomXMLNode.ChildNodes Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CustomXMLNodes collection containing all of the child elements of the current node. Read-only.

Syntax

expression .ChildNodes

expression An expression that returns a CustomXMLNode object.

Return Value

CustomXMLNodes

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.Creator Property (Office)

 Copy code hover
[image]

CustomXMLNode.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CustomXMLNode object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a CustomXMLNode object.

Return Value

Long

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.FirstChild Property (Office)

 Copy code hover
[image]

CustomXMLNode.FirstChild Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CustomXMLNode object corresponding to the first child element of the current node. If the node has no child elements (or if it isn't of type msoCustomXMLNodeElement), returns Nothing. Read-only.

Syntax

expression .FirstChild

expression An expression that returns a CustomXMLNode object.

Return Value

CustomXMLNode

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.LastChild Property (Office)

 Copy code hover
[image]

CustomXMLNode.LastChild Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CustomXMLNode object corresponding to the last child element of the current node. If the node has no child elements (or if it is not of type msoCustomXMLNodeElement), the property returns Nothing. Read-only.

Syntax

expression .LastChild

expression An expression that returns a CustomXMLNode object.

Return Value

CustomXMLNode

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.NamespaceURI Property (Office)

 Copy code hover
[image]

CustomXMLNode.NamespaceURI Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the unique address identifier for the namespace of the CustomXMLNode object. Read-only.

Syntax

expression .NamespaceURI

expression An expression that returns a CustomXMLNode object.

Return Value

String

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.NextSibling Property (Office)

 Copy code hover
[image]

CustomXMLNode.NextSibling Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the next sibling node (element, comment, or processing instruction) of the current node. If the node is the last sibling at its level, the property returns Nothing. Read-only.

Syntax

expression .NextSibling

expression An expression that returns a CustomXMLNode object.

Return Value

CustomXMLNode

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.NodeType Property (Office)

 Copy code hover
[image]

CustomXMLNode.NodeType Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the type of the current node. Read-only.

Syntax

expression .NodeType

expression An expression that returns a CustomXMLNode object.

Return Value

MsoCustomXMLNodeType

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.NodeValue Property (Office)

 Copy code hover
[image]

CustomXMLNode.NodeValue Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the value of the current node. Read/write.

Syntax

expression .NodeValue

expression An expression that returns a CustomXMLNode object.

Return Value

String

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.OwnerDocument Property (Office)

 Copy code hover
[image]

CustomXMLNode.OwnerDocument Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the object representing the Microsoft Excel workbook, Microsoft PowerPoint presentation, or the Microsoft Word document associated with this node. Read-only.

Syntax

expression .OwnerDocument

expression An expression that returns a CustomXMLNode object.

Return Value

Object

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.OwnerPart Property (Office)

 Copy code hover
[image]

CustomXMLNode.OwnerPart Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the object representing the part associated with this node. Read-only.

Syntax

expression .OwnerPart

expression An expression that returns a CustomXMLNode object.

Return Value

CustomXMLPart

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.Parent Property (Office)

 Copy code hover
[image]

CustomXMLNode.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CustomXMLNode object. Read-only.

Syntax

expression .Parent

expression An expression that returns a CustomXMLNode object.

Return Value

Object

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.ParentNode Property (Office)

 Copy code hover
[image]

CustomXMLNode.ParentNode Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the parent element node of the current node. If the current node is at the root level, the property returns Nothing. Read-only.

Syntax

expression .ParentNode

expression An expression that returns a CustomXMLNode object.

Return Value

CustomXMLNode

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.PreviousSibling Property (Office)

 Copy code hover
[image]

CustomXMLNode.PreviousSibling Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the previous sibling node (element, comment, or processing instruction) of the current node. If the current node is the first sibling at its level, the property returns Nothing. Read-only.

Syntax

expression .PreviousSibling

expression An expression that returns a CustomXMLNode object.

Return Value

CustomXMLNode

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.Text Property (Office)

 Copy code hover
[image]

CustomXMLNode.Text Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the text for the current node. Read/write.

Syntax

expression .Text

expression An expression that returns a CustomXMLNode object.

Return Value

String

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.XML Property (Office)

 Copy code hover
[image]

CustomXMLNode.XML Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the XML representation of the current node and its children, if any exist. Read-only.

Syntax

expression .XML

expression An expression that returns a CustomXMLNode object.

Return Value

String

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.XPath Property (Office)

 Copy code hover
[image]

CustomXMLNode.XPath Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a String with the canonicalized XPath for the current node. If the node is no longer in the Document Object Model (DOM), the property returns an error message. Read-only.

Syntax

expression .XPath

expression An expression that returns a CustomXMLNode object.

Return Value

String

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode Methods (Office)

 Copy code hover
[image]

CustomXMLNode Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
AppendChildNode | Appends a single node as the last child under the context element node in the tree.
AppendChildSubtree | Adds a subtree as the last child under the context element node in the tree.
Delete | Deletes the current node from the tree (including all of its children, if any exist).
HasChildNodes | Gets True if the current element node has child element nodes.
InsertNodeBefore | Inserts a new node just before the context node in the tree.
InsertSubtreeBefore | Inserts the specified subtree into the location just before the context node.
RemoveChild | Removes the specified child node from the tree.
ReplaceChildNode | Removes the specified child node (and its subtree) from the main tree, and replaces it with a different node in the same location.
ReplaceChildSubtree | Removes the specified node (and its subtree) from the main tree, and replaces it with a different subtree in the same location.
SelectNodes | Selects a collection of nodes matching an XPath expression. This method differs from the CustomXMLPart.SelectNodes method in that the XPath expression will be evaluated starting with the 'expression' node as the context node.
SelectSingleNode | Selects a single node from a collection matching an XPath expression. This method differs from the CustomXMLPart.SelectSingleNode method in that the XPath expression will be evaluated starting with the 'expression' node as the context node.


CustomXMLNode.AppendChildNode Method (Office)

 Copy code hover
[image]

CustomXMLNode.AppendChildNode Method (Office)
See also Send feedback

Published: July 09, 2012

Appends a single node as the last child under the context element node in the tree.

Syntax

expression .AppendChildNode(Name, NamespaceURI, NodeType, NodeValue)

expression An expression that returns a CustomXMLNode object.

Parameters

Name | Required/Optional | Data Type | Description
Name | Optional | String | Represents the base name of the element to be appended.
NamespaceURI | Optional | String | Represents the namespace of the element to be appended. This parameter is required to append nodes of type msoCustomXMLNodeElement or msoCustomXMLNodeAttribute, otherwise it is ignored.
NodeType | Optional | MsoCustomXMLNodeType | Specifies the type of node to append. If the parameter is not specified, it is assumed to be of type msoCustomXMLNodeElement.
NodeValue | Optional | String | Used to set the value of the appended node for those nodes that allow text. If the node doesn't allow text, the parameter is ignored.

Remarks

If the context node is any type other than msoXMLNodeElement, or if the operation would result in an invalid tree structure, the append is not performed and an error message is displayed.

Example

The following example demonstrates appending a CustomXMLNode object to another node.

VBA Copy code Copy code
Sub AppendNode()
    Dim cxp1 As CustomXMLPart
    Dim cxn As CustomXMLNode

    With ActiveDocument

        ' Add and populate a custom xml part
        set cxp1 = .CustomXMLParts.Add "<invoice />"

        ' Add a node
        cxp1.AddNode "/invoice", "upccode", "urn:invoice:namespace"

        Set cxn = cxp1.SelectSingleNode("//*[@quantity < 4]")

        ' Append a child node to the single node selected previously.
        cxn.AppendChildNode("discount", "urn:invoice:namespace", "string", "0.10")

    End With

End Sub

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.AppendChildSubtree Method (Office)

 Copy code hover
[image]

CustomXMLNode.AppendChildSubtree Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a subtree as the last child under the context element node in the tree.

Syntax

expression .AppendChildSubtree(XML)

expression An expression that returns a CustomXMLNode object.

Parameters

Name | Required/Optional | Data Type | Description
XML | Required | String | Represents the subtree to add.

Remarks

If the context node is any type other than msoXMLNodeElement, the append operation is not performed and an error message is displayed. If the CustomXMLNode is being validated against a schema and if the operation would result in an invalid tree structure, the append operation is not performed and an error message is displayed.

Example

The following example demonstrates appending a node to an existing node.

VBA Copy code Copy code
Sub ShowCustomXmlParts()
    Dim cxp1 As CustomXMLPart
    Dim cxn As CustomXMLNode

    With ActiveDocument

        ' Add and populate a custom xml part
        set cxp1 = .CustomXMLParts.Add "<invoice />"

        ' Get nodes using XPath.
        Set cxn = cxp1.SelectSingleNode("//*[@quantity < 4]")

        ' Append a child subtree to the single node selected previously.
        cxn.AppendChildSubtree("<discounts><discount>0.10</discount></discounts>")

    End With

End Sub

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.Delete Method (Office)

 Copy code hover
[image]

CustomXMLNode.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the current node from the tree (including all of its children, if any exist).

Syntax

expression .Delete

expression An expression that returns a CustomXMLNode object.

Remarks

If the operation would result in an invalid tree structure, the deletion is not performed and an error message is displayed.

Example

The following example demonstrates using various methods to add custom XML parts, select parts and nodes with different criteria, append child subtrees, and delete parts and nodes.

VBA Copy code Copy code
Sub ShowCustomXmlParts()
    On Error GoTo Err

    Dim cxps As CustomXMLParts
    Dim cxp1 As CustomXMLPart
    Dim cxp2 As CustomXMLPart
    Dim cxn As CustomXMLNode
    Dim cxns As CustomXMLNodes
    Dim strXml As String
    Dim strUri As String

    With ActiveDocument
        ' Example written for Word.

        ' Adding a custom XML part.
        .CustomXMLParts.Add "<custXMLPart />"

        ' Add and then load from a file.
        Set cxp1 = .CustomXMLParts.Add
        cxp1.Load "c:\invoice.xml"

        ' Returns the first custom XML part with the given root namespace.
        Set cxp2 = .CustomXMLParts("urn:invoice:namespace")     '

        ' Access all with a given root namespace; returns the entire collection.
        Set cxps = .CustomXMLParts.SelectByNamespace("urn:invoice:namespace")

        ' DOM-type operations.
        ' Get the XML.
        strXml = cxp2.XML
        ' Get the root namespace
        strUri = cxp2.NamespaceURI
        ' Get nodes using XPath.
        Set cxn = cxp2.SelectSingleNode("//*[@quantity < 4]")
        Set cxns = cxp2.SelectNodes("//*[@unitPrice > 20]")
        ' Append a child subtree to the single node selected previously.
        cxn.AppendChildSubtree("<discounts><discount>0.10</discount></discounts>")

        ' Delete custom XML part and node and its children.
        cxp2.Delete
        cxn.Delete

    End With

    Exit Sub

' Exception handling. Show the message and resume.
Err:
        MsgBox (Err.Description)
        Resume Next
End Sub

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.HasChildNodes Method (Office)

 Copy code hover
[image]

CustomXMLNode.HasChildNodes Method (Office)
See also Send feedback

Published: July 09, 2012

Gets True if the current element node has child element nodes.

Syntax

expression .HasChildNodes

expression An expression that returns a CustomXMLNode object.

Return Value

Boolean

Remarks

This method will always return False when CustomXMLNode isn't of node type msoCustomXMLNodeElement.

Example

The following example demonstrates using various methods to add custom XML parts, select parts and nodes with different criteria, append child subtrees, tests whether the subtree was successfully added, and delete parts and nodes.

VBA Copy code Copy code
Sub ShowCustomXmlParts()
    On Error GoTo Err

    Dim cxps As CustomXMLParts
    Dim cxp1 As CustomXMLPart
    Dim cxp2 As CustomXMLPart
    Dim cxn As CustomXMLNode
    Dim cxns As CustomXMLNodes
    Dim strXml As String
    Dim strUri As String

    With ActiveDocument
        ' Example written for Word.

        ' Adding a custom XML part.
        .CustomXMLParts.Add "<custXMLPart />"

        ' Add and then load from a file.
        Set cxp1 = .CustomXMLParts.Add
        cxp1.Load "c:\invoice.xml"

        ' Returns the first custom XML part with the given root namespace.
        Set cxp2 = .CustomXMLParts("urn:invoice:namespace")     '

        ' Access all with a given root namespace; returns the entire collection.
        Set cxps = .CustomXMLParts.SelectByNamespace("urn:invoice:namespace")

        ' DOM-type operations.
        ' Get the XML.
        strXml = cxp2.XML
        ' Get the root namespace.
        strUri = cxp2.NamespaceURI
        ' Get nodes using XPath.
        Set cxn = cxp2.SelectSingleNode("//*[@quantity < 4]")
        Set cxns = cxp2.SelectNodes("//*[@unitPrice > 20]")
        ' Append a child subtree to the single node selected previously.
        cxn.AppendChildSubtree("<discounts><discount>0.10</discount></discounts>")

         ' Tell user that the child subtree was added.
         If  cxn.HasChildNodes then
            MsgBox("The 'Discounts' nodes were added.")
         Else
            MsgBox("The 'Discounts' nodes were not added.")
         End If

        ' Delete custom XML part and node and its children.
        cxp2.Delete
        cxn.Delete

    End With

    Exit Sub

' Exception handling. Show the message and resume.
Err:
        MsgBox (Err.Description)
        Resume Next
End Sub

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.InsertNodeBefore Method (Office)

 Copy code hover
[image]

CustomXMLNode.InsertNodeBefore Method (Office)
See also Send feedback

Published: July 09, 2012

Inserts a new node just before the context node in the tree.

Syntax

expression .InsertNodeBefore(Name, NamespaceURI, NodeType, NodeValue, NextSibling)

expression An expression that returns a CustomXMLNode object.

Parameters

Name | Required/Optional | Data Type | Description
Name | Optional | String | Represents the base name of the node to be added.
NamespaceURI | Optional | String | Represents the namespace of the element to be added. This parameter is required if adding nodes of type msoCustomXMLNodeElement or msoCustomXMLNodeAttribute, otherwise it is ignored.
NodeType | Optional | MsoCustomXMLNodeType | Specifies the type of the node to be added. If the parameter is not specified, it is assumed to be a node of type msoCustomXMLNodeElement.
NodeValue | Optional | String | Used to set the value of the node to be added for those nodes that allow text. If the node doesn't allow text, the parameter is ignored.
NextSibling | Optional | CustomXMLNode | Represents the context node.

Remarks

If the context node is not present when adding a node of type msoCustomXMLNodeElement, msoCustomXMLNodeComment, or msoCustomXMLNodeProcessingInstruction, the new node is added to the last child of the context node. If the operation would result in an invalid tree structure, the insertion is not performed and an error message is displayed.

Example

The following example adds a custom part and then finds a node in that part by using an XPath expression. The code then inserts a node before the found node.

VBA Copy code Copy code
Dim cxp1 As CustomXMLPart
Dim cxn As CustomXMLNode

With ActiveDocument

   ' Add a custom xml part.
   .CustomXMLParts.Add "<invoice>"

   ' Returns the first custom xml part with the given root namespace.
   Set cxp1 = .CustomXMLParts("urn:invoice:namespace")

   ' Get node using XPath.
   Set cxn = cxp1.SelectSingleNode("//*[@supplier = "Contoso"]")

   ' Insert a node before the single node selected previously.
    cxn.InsertNodeBefore("discount", "urn:invoice:namespace")

 End With

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.InsertSubtreeBefore Method (Office)

 Copy code hover
[image]

CustomXMLNode.InsertSubtreeBefore Method (Office)
See also Send feedback

Published: July 09, 2012

Inserts the specified subtree into the location just before the context node.

Syntax

expression .InsertSubtreeBefore(XML, NextSibling)

expression An expression that returns a CustomXMLNode object.

Parameters

Name | Required/Optional | Data Type | Description
XML | Required | String | Represents the subtree to be added.
NextSibling | Optional | CustomXMLNode | Specifies the context node.

Remarks

If the NextSibling parameter is not a child of the context node or if the operation would result in an invalid tree structure, the insertion is not performed and an error message is displayed.

Example

The following example adds a custom part and then finds a node in that part by using an XPath expression. The code then inserts a node after the found node.

VBA Copy code Copy code
Dim cxp1 As CustomXMLPart
Dim cxn As CustomXMLNode

With ActiveDocument

   ' Add a custom xml part.
   .CustomXMLParts.Add "<invoice>"

   ' Returns the first custom xml part with the given root namespace.
   Set cxp1 = .CustomXMLParts("urn:invoice:namespace")

   ' Get nodes using XPath.
   Set cxn = cxp1.SelectSingleNode("//*[@supplier = "Contoso"]")

   ' Insert a node before the single node selected previously.
    cxn.InsertNodeAfter("discount", "urn:invoice:namespace")

 End With

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.RemoveChild Method (Office)

 Copy code hover
[image]

CustomXMLNode.RemoveChild Method (Office)
See also Send feedback

Published: July 09, 2012

Removes the specified child node from the tree.

Syntax

expression .RemoveChild(Child)

expression An expression that returns a CustomXMLNode object.

Parameters

Name | Required/Optional | Data Type | Description
Child | Required | CustomXMLNode | Represents the child node of the context node.

Remarks

If the node specified in the Child parameter is not a child of the context node or if the action would result in an invalid tree, the removal is not performed and an error message is displayed.

Example

The following example selects a custom part and then a node in that part. The code then removes a child of that node.

VBA Copy code Copy code
Dim cxp1 As CustomXMLPart
 Dim cxn As CustomXMLNode

 With ActiveDocument

    ' Return the first part with the given root namespace.
    Set cxp1 = .CustomXMLParts("urn:invoice:namespace")

    ' Get node using XPath expression.
    Set cxn = cxp1.SelectSingleNode("//*[@supplierID = 1]")

    ' Remove a child node.
    cxn.RemoveChild(cxn.SelectSingleNode("//discount"))

End With

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.ReplaceChildNode Method (Office)

 Copy code hover
[image]

CustomXMLNode.ReplaceChildNode Method (Office)
See also Send feedback

Published: July 09, 2012

Removes the specified child node (and its subtree) from the main tree, and replaces it with a different node in the same location.

Syntax

expression .ReplaceChildNode(OldNode, Name, NamespaceURI, NodeType, NodeValue)

expression An expression that returns a CustomXMLNode object.

Parameters

Name | Required/Optional | Data Type | Description
OldNode | Required | CustomXMLNode | Represents the child node to be replaced.
Name | Optional | String | Represents the base name of the element to be added.
NamespaceURI | Optional | String | Represents the namespace of the element to be added. This parameter is required if adding nodes of type msoCustomXMLNodeElement or msoCustomXMLNodeAttribute, otherwise it is ignored.
NodeType | Optional | MsoCustomXMLNodeType | Specifies the type of node to add. If the parameter is not specified, it is assumed to be of type msoCustomXMLNodeElement.
NodeValue | Optional | String | Used to set the value of the node to be added for those nodes that allow text. If the node doesn't allow text, the parameter is ignored.

Remarks

If the OldNode parameter is not a child of the context node or if the operation would result in an invalid tree structure, the replacement is not performed and an error message is displayed. In addition, in a case where the node to be added already exists, the replacement is not performed and an error message is displayed.

Example

The following example selects a custom part and then a node in that part. The code then replaces a child of that node with another node.

VBA Copy code Copy code
Dim cxp1 As CustomXMLPart
Dim cxn As CustomXMLNode

With ActiveDocument

   ' Return the first custom xml part with the given root namespace.
   Set cxp1 = .CustomXMLParts("urn:invoice:namespace")     '

   Set cxn = cxp1.SelectSingleNode("//*[@supplierID = 1]")

   ' Replace a child node.
    cxn.ReplaceChildNode(cxn.SelectSingleNode("//discount", "rebate")

End With

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.ReplaceChildSubtree Method (Office)

 Copy code hover
[image]

CustomXMLNode.ReplaceChildSubtree Method (Office)
See also Send feedback

Published: July 09, 2012

Removes the specified node (and its subtree) from the main tree, and replaces it with a different subtree in the same location.

Syntax

expression .ReplaceChildSubtree(XML, OldNode)

expression An expression that returns a CustomXMLNode object.

Parameters

Name | Required/Optional | Data Type | Description
XML | Required | String | Represents the subtree to be added.
OldNode | Required | CustomXMLNode | Represents the child node to be replaced.

Remarks

If the operation would result in an invalid tree structure, the replacement operation is not performed and an error message is displayed.

Example

The following example selects a custom part and then a node in that part. The code then replaces a child subtree of that node with another subtree.

VBA Copy code Copy code
Dim cxp1 As CustomXMLPart
Dim cxn As CustomXMLNode

With ActiveDocument

    ' Return the first custom xml part with the given root namespace.
    Set cxp1 = .CustomXMLParts("urn:invoice:namespace")     '

    ' Get node using XPath expression.
    Set cxn = cxp1.SelectSingleNode("//*[@supplierID = 1]")

    ' Replace one subtree and its children with another.
   cxn.ReplaceChildSubtree("<rebates><rebate>0.10</rebate></rebates>", "//discounts")

 End With

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.SelectNodes Method (Office)

 Copy code hover
[image]

CustomXMLNode.SelectNodes Method (Office)
See also Send feedback

Published: July 09, 2012

Selects a collection of nodes matching an XPath expression. This method differs from the CustomXMLPart.SelectNodes method in that the XPath expression will be evaluated starting with the 'expression' node as the context node.

Syntax

expression .SelectNodes(XPath)

expression An expression that returns a CustomXMLNode object.

Parameters

Name | Required/Optional | Data Type | Description
XPath | Required | String | Contains an XPath expression.

Return Value

CustomXMLNodes

Example

The following example demonstrates adding a custom XML part, selecting a part matching a namespace URI, and then selecting nodes within that part that match an XPath expression.

VBA Copy code Copy code
Dim cxp1 As CustomXMLPart
Dim cxn As CustomXMLNode

' Add a custom xml part.
ActiveDocument.CustomXMLParts.Add "<supplier>"

' Return the first custom xml part with the given namespace.
Set cxp1 = ActiveDocument.CustomXMLParts("urn:invoice:namespace")

' Get all of the nodes matching an XPath expression.
 Set cxns = cxp1.SelectNodes("//*[@unitPrice > 20]")

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNode.SelectSingleNode Method (Office)

 Copy code hover
[image]

CustomXMLNode.SelectSingleNode Method (Office)
See also Send feedback

Published: July 09, 2012

Selects a single node from a collection matching an XPath expression. This method differs from the CustomXMLPart.SelectSingleNode method in that the XPath expression will be evaluated starting with the 'expression' node as the context node.

Syntax

expression .SelectSingleNode(XPath)

expression An expression that returns a CustomXMLNode object.

Parameters

Name | Required/Optional | Data Type | Description
XPath | Required | String | Contains an XPath expression.

Return Value

CustomXMLNode

Remarks

The prefix mappings for the XPath expression are retrieved from the NamespaceManager property.

Example

The following example demonstrates adding a custom XML part, selecting a part with a namespace URI, and then selecting a node within that part that matches an XPath expression.

VBA Copy code Copy code
Dim cxp1 As CustomXMLPart
Dim cxn As CustomXMLNode

' Add a custom xml part.
ActiveDocument.CustomXMLParts.Add "<supplier>"

' Return the first custom xml part with the given namespace.
Set cxp1 = ActiveDocument.CustomXMLParts("urn:invoice:namespace")

' Get a node using XPath.
 Set cxn = cxp1(1).SelectSingleNode("//*[@supplierID = 1]")

See also

Concepts

CustomXMLNode Object

Other resources

CustomXMLNode Object Members


CustomXMLNodes Object (Office)

 Copy code hover
[image]

CustomXMLNodes Object (Office)
See also Send feedback

Published: July 09, 2012

Contains a collection of CustomXMLNodes objects representing the XML nodes in a document.

Remarks

The Attributes and the ChildNodes properties return collections of nodes of this type.

Example

The following example selects one or more matching the XPath expression.

VBA Copy code Copy code
Sub CustomXmlNodes()
    Dim cxp1 As CustomXMLPart
    Dim cxns As CustomXMLNodes

    With ActiveDocument

        ' Returns the first custom xml part with the given root namespace.
        Set cxp1 = .CustomXMLParts("urn:invoice:namespace")

        ' Get custom xml nodes using XPath.
        Set cxns = cxp1.SelectNodes("//*[@unitPrice > 20]")

    End With

End Sub

See also

Concepts

Object Model Reference

Other resources

CustomXMLNodes Object Members


CustomXMLNodes Members (Office)

 Copy code hover
[image]

CustomXMLNodes Members (Office)
Send feedback

Published: July 09, 2012

Contains a collection of CustomXMLNodes objects representing the XML nodes in a document.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLNodes object. Read-only.
Count | Gets a count of the number of CustomXMLNode objects in a CustomXMLNodes collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLNodes object was created. Read-only.
Item | Gets a CustomXMLNode object from the CustomXMLNodes collection. Read-only.
Parent | Gets the Parent object for the CustomXMLNodes object. Read-only.


CustomXMLNodes Properties (Office)

 Copy code hover
[image]

CustomXMLNodes Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLNodes object. Read-only.
Count | Gets a count of the number of CustomXMLNode objects in a CustomXMLNodes collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLNodes object was created. Read-only.
Item | Gets a CustomXMLNode object from the CustomXMLNodes collection. Read-only.
Parent | Gets the Parent object for the CustomXMLNodes object. Read-only.


CustomXMLNodes.Application Property (Office)

 Copy code hover
[image]

CustomXMLNodes.Application Property (Office)
See also Send feedback

Gets an Application object that represents the container application for the CustomXMLNodes object. Read-only.

Syntax

expression .Application

expression An expression that returns a CustomXMLNodes object.

Return Value

Object

See also

Concepts

CustomXMLNodes Object

Other resources

CustomXMLNodes Object Members


CustomXMLNodes.Count Property (Office)

 Copy code hover
[image]

CustomXMLNodes.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a count of the number of CustomXMLNode objects in a CustomXMLNodes collection. Read-only.

Syntax

expression .Count

expression An expression that returns a CustomXMLNodes object.

Return Value

Long

See also

Concepts

CustomXMLNodes Object

Other resources

CustomXMLNodes Object Members


CustomXMLNodes.Creator Property (Office)

 Copy code hover
[image]

CustomXMLNodes.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CustomXMLNodes object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a CustomXMLNodes object.

Return Value

Long

See also

Concepts

CustomXMLNodes Object

Other resources

CustomXMLNodes Object Members


CustomXMLNodes.Item Property (Office)

 Copy code hover
[image]

CustomXMLNodes.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CustomXMLNode object from the CustomXMLNodes collection. Read-only.

Syntax

expression .Item(Index)

expression An expression that returns a CustomXMLNodes object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | The index number of the CustomXMLNode object to be returned.

Return Value

CustomXMLNode

See also

Concepts

CustomXMLNodes Object

Other resources

CustomXMLNodes Object Members


CustomXMLNodes.Parent Property (Office)

 Copy code hover
[image]

CustomXMLNodes.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CustomXMLNodes object. Read-only.

Syntax

expression .Parent

expression An expression that returns a CustomXMLNodes object.

Return Value

Object

See also

Concepts

CustomXMLNodes Object

Other resources

CustomXMLNodes Object Members


CustomXMLPart Object (Office)

 Copy code hover
[image]

CustomXMLPart Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a single CustomXMLPart in a CustomXMLParts collection.

Example

The following example adds a part to a CustomXMLPart object.

VBA Copy code Copy code
Sub AddPartToCollection()
    Dim myPart As CustomXMLPart

    Set myPart = ActiveDocument.CustomXMLParts.Add("<author>Mark Twain</author>")

End Sub

See also

Concepts

Object Model Reference

Other resources

CustomXMLPart Object Members


CustomXMLPart Members (Office)

 Copy code hover
[image]

CustomXMLPart Members (Office)
Send feedback

Published: July 09, 2012

Represents a single CustomXMLPart in a CustomXMLParts collection.

Events

Name | Description
NodeAfterDelete | Occurs after a node is deleted in a CustomXMLPart object.
NodeAfterInsert | Occurs after a node is inserted in a CustomXMLPart object.
NodeAfterReplace | Occurs just after a node is replaced in a CustomXMLPart object.

Methods

Name | Description
AddNode | Adds a node to the XML tree.
Delete | Deletes the current CustomXMLPart from the data store (IXMLDataStore interface).
Load | Allows the template author to populate a CustomXMLPart from an existing file. Returns True if the load was successful.
LoadXML | Allows the template author to populate a CustomXMLPart object from an XML string. Returns True if the load was successful.
SelectNodes | Selects a collection of nodes from a custom XML part.
SelectSingleNode | Selects a single node within a custom XML part matching an XPath expression.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLPart object. Read-only.
BuiltIn | Gets a value that indicates whether the CustomXMLPart is built-in. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLPart object was created. Read-only.
DocumentElement | Gets the root element of a bound region of data in a document. If the region is empty, the property returns Nothing. Read-only.
Errors | Gets a CustomXMLValidationErrors object that provides access to any XML validation errors, if any exists. If no validation errors exist, this property returns Nothing. Read-only.
Id | Gets a String containing the GUID assigned to the current CustomXMLPart object. Read-only.
NamespaceManager | Gets the set of namespace prefix mappings used against the current CustomXMLPart object. Read-only.
NamespaceURI | Gets the unique address identifier for the namespace of the CustomXMLPart object. Read-only.
Parent | Gets the Parent object for the CustomXMLPart object. Read-only.
SchemaCollection | Gets or sets a CustomXMLSchemaCollection object representing the set of schemas attached to a bound region of data in a document. Read/write.
XML | Gets the XML representation of the current CustomXMLPart object. Read-only.


CustomXMLPart Properties (Office)

 Copy code hover
[image]

CustomXMLPart Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLPart object. Read-only.
BuiltIn | Gets a value that indicates whether the CustomXMLPart is built-in. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLPart object was created. Read-only.
DocumentElement | Gets the root element of a bound region of data in a document. If the region is empty, the property returns Nothing. Read-only.
Errors | Gets a CustomXMLValidationErrors object that provides access to any XML validation errors, if any exists. If no validation errors exist, this property returns Nothing. Read-only.
Id | Gets a String containing the GUID assigned to the current CustomXMLPart object. Read-only.
NamespaceManager | Gets the set of namespace prefix mappings used against the current CustomXMLPart object. Read-only.
NamespaceURI | Gets the unique address identifier for the namespace of the CustomXMLPart object. Read-only.
Parent | Gets the Parent object for the CustomXMLPart object. Read-only.
SchemaCollection | Gets or sets a CustomXMLSchemaCollection object representing the set of schemas attached to a bound region of data in a document. Read/write.
XML | Gets the XML representation of the current CustomXMLPart object. Read-only.


CustomXMLPart.Application Property (Office)

 Copy code hover
[image]

CustomXMLPart.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the CustomXMLPart object. Read-only.

Syntax

expression .Application

expression An expression that returns a CustomXMLPart object.

Return Value

Object

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.BuiltIn Property (Office)

 Copy code hover
[image]

CustomXMLPart.BuiltIn Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value that indicates whether the CustomXMLPart is built-in. Read-only

Syntax

expression .BuiltIn

expression An expression that returns a CustomXMLPart object.

Return Value

Boolean

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.Creator Property (Office)

 Copy code hover
[image]

CustomXMLPart.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CustomXMLPart object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a CustomXMLPart object.

Return Value

Long

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.DocumentElement Property (Office)

 Copy code hover
[image]

CustomXMLPart.DocumentElement Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the root element of a bound region of data in a document. If the region is empty, the property returns Nothing. Read-only.

Syntax

expression .DocumentElement

expression An expression that returns a CustomXMLPart object.

Return Value

CustomXMLNode

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.Errors Property (Office)

 Copy code hover
[image]

CustomXMLPart.Errors Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CustomXMLValidationErrors object that provides access to any XML validation errors, if any exists. If no validation errors exist, this property returns Nothing. Read-only.

Syntax

expression .Errors

expression An expression that returns a CustomXMLPart object.

Return Value

CustomXMLValidationErrors

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.Id Property (Office)

 Copy code hover
[image]

CustomXMLPart.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a String containing the GUID assigned to the current CustomXMLPart object. Read-only.

Syntax

expression .Id

expression An expression that returns a CustomXMLPart object.

Return Value

String

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.NamespaceManager Property (Office)

 Copy code hover
[image]

CustomXMLPart.NamespaceManager Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the set of namespace prefix mappings used against the current CustomXMLPart object. Read-only.

Syntax

expression .NamespaceManager

expression An expression that returns a CustomXMLPart object.

Return Value

CustomXMLPrefixMappings

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.NamespaceURI Property (Office)

 Copy code hover
[image]

CustomXMLPart.NamespaceURI Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the unique address identifier for the namespace of the CustomXMLPart object. Read-only.

Syntax

expression .NamespaceURI

expression An expression that returns a CustomXMLPart object.

Return Value

String

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.Parent Property (Office)

 Copy code hover
[image]

CustomXMLPart.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CustomXMLPart object. Read-only.

Syntax

expression .Parent

expression An expression that returns a CustomXMLPart object.

Return Value

Object

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.SchemaCollection Property (Office)

 Copy code hover
[image]

CustomXMLPart.SchemaCollection Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a CustomXMLSchemaCollection object representing the set of schemas attached to a bound region of data in a document. Read/write.

Syntax

expression .SchemaCollection

expression An expression that returns a CustomXMLPart object.

Return Value

CustomXMLSchemaCollection

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.XML Property (Office)

 Copy code hover
[image]

CustomXMLPart.XML Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the XML representation of the current CustomXMLPart object. Read-only.

Syntax

expression .XML

expression An expression that returns a CustomXMLPart object.

Return Value

String

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart Methods (Office)

 Copy code hover
[image]

CustomXMLPart Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
AddNode | Adds a node to the XML tree.
Delete | Deletes the current CustomXMLPart from the data store (IXMLDataStore interface).
Load | Allows the template author to populate a CustomXMLPart from an existing file. Returns True if the load was successful.
LoadXML | Allows the template author to populate a CustomXMLPart object from an XML string. Returns True if the load was successful.
SelectNodes | Selects a collection of nodes from a custom XML part.
SelectSingleNode | Selects a single node within a custom XML part matching an XPath expression.


CustomXMLPart.AddNode Method (Office)

 Copy code hover
[image]

CustomXMLPart.AddNode Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a node to the XML tree.

Syntax

expression .AddNode(Parent, Name, NamespaceURI, NextSibling, NodeType, NodeValue)

expression An expression that returns a CustomXMLPart object.

Parameters

Name | Required/Optional | Data Type | Description
Parent | Required | CustomXMLNode | Represents the node under which this node should be added. If adding an attribute, the parameter denotes the element that the attribute should be added to.
Name | Optional | String | Represents the base name of the node to be added.
NamespaceURI | Optional | String | Represents the namespace of the element to be appended. This parameter is required to append nodes of type msoCustomXMLNodeElement or msoCustomXMLNodeAttribute, otherwise it is ignored.
NextSibling | Optional | CustomXMLNode | Represents the node which should become the next sibling of the new node. If not specified, the node is added to the end of the parent node's children. This parameter is ignored for additions of type msoXMLNodeAttribute. If the node is not a child of the parent, an error is displayed.
NodeType | Optional | MsoCustomXMLNodeType | Specifies the type of node to append. If the parameter is not specified, it is assumed to be of type msoCustomXMLNodeElement.
NodeValue | Optional | String | Used to set the value of the appended node for those nodes that allow text. If the node doesn't allow text, the parameter is ignored.

Remarks

If the AddNode operation would result in an invalid tree structure, the append is not performed and an error message is displayed.

Example

The following example demonstrates adding a node to a CustomXMLPart object.

VBA Copy code Copy code
Sub AddNodeCustomXmlParts()

    Dim cxp1 As CustomXMLPart
    Dim cxn As CustomXMLNode

    With ActiveDocument
        ' Add and populate a custom xml part
        Set cxp1 = .CustomXMLParts.Add("<invoice />")

        ' Set the parent node
        Set cxn = cxp1.SelectSingleNode("/invoice")

        ' Add a node under the parent node
        cxp1.AddNode cxn, "upccode", "urn:invoice:namespace"

    End With

End Sub

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.Delete Method (Office)

 Copy code hover
[image]

CustomXMLPart.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the current CustomXMLPart from the data store (IXMLDataStore interface).

Syntax

expression .Delete

expression An expression that returns a CustomXMLPart object.

Remarks

If you attempt to delete the part containing the core properties, the operation is not performed and an error message is displayed.

Example

The following example adds a custom XML part, select a node with a criteria, and delete the part and node.

VBA Copy code Copy code
Sub ShowCustomXmlParts()
    On Error GoTo Err

    Dim cxp1 As CustomXMLPart
    Dim cxn As CustomXMLNode

    With ActiveDocument
        ' Example written for Word.

        ' Add and then load from a file.
        Set cxp1 = .CustomXMLParts.Add
        cxp1.Load "c:\invoice.xml"

        Set cxn = cxp1.SelectSingleNode("//*[@quantity < 4]")
        ' Insert a subtree before the single node selected previously.
        cxn.InsertSubTreeBefore("<discounts><discount>0.10</discount></discounts>")

        ' Delete custom XML part.
        cxp1.Delete
        cxn.Delete

    End With

    Exit Sub

' Exception handling. Show the message and resume.
Err:
        MsgBox (Err.Description)
        Resume Next
End Sub

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.Load Method (Office)

 Copy code hover
[image]

CustomXMLPart.Load Method (Office)
See also Send feedback

Published: July 09, 2012

Allows the template author to populate a CustomXMLPart from an existing file. Returns True if the load was successful.

Syntax

expression .Load(FilePath)

expression An expression that returns a CustomXMLPart object.

Parameters

Name | Required/Optional | Data Type | Description
FilePath | Required | String | Points to the file on the user's computer or on a network containing the XML to be loaded.

Return Value

Boolean

Example

The following example adds a custom XML part, populates the custom XML part with XML from a file, and then manipulates the part's nodes.

VBA Copy code Copy code
Sub ShowCustomXmlParts()
    On Error GoTo Err

    Dim cxp1 As CustomXMLPart

    With ActiveDocument
        ' Example written for Word.

        ' Add a custom XML part and then load the XML from a file.
        Set cxp1 = .CustomXMLParts.Add
        cxp1.Load "c:\invoice.xml"

        Set cxn = cxp1.SelectSingleNode("//*[@quantity < 4]")
        ' Insert a subtree before the single node selected previously.
        cxn.InsertSubTreeBefore("<discounts><discount>0.10</discount></discounts>")

        ' Delete custom XML part.
        cxp1.Delete
        cxn.Delete

    End With

    Exit Sub

' Exception handling. Show the message and resume.
Err:
        MsgBox (Err.Description)
        Resume Next
End Sub

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.LoadXML Method (Office)

 Copy code hover
[image]

CustomXMLPart.LoadXML Method (Office)
See also Send feedback

Published: July 09, 2012

Allows the template author to populate a CustomXMLPart object from an XML string. Returns True if the load was successful.

Syntax

expression .LoadXML(XML)

expression An expression that returns a CustomXMLPart object.

Parameters

Name | Required/Optional | Data Type | Description
XML | Required | String | Contains the XML to load.

Return Value

Boolean

Example

The following example loads XML into a custom XML part from a string.

VBA Copy code Copy code
Sub ShowCustomXmlParts()
    On Error GoTo Err

    Dim cxp1 As CustomXMLPart

        ' Add a custom XML part and then load the XML.
        Set cxp1 = ActiveDocument.CustomXMLParts.Add
        cxp1.LoadXML("<discounts><discount>0.10</discount></discounts>")

    Exit Sub

' Exception handling. Show the message and resume.
Err:
        MsgBox (Err.Description)
        Resume Next
End Sub

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.SelectNodes Method (Office)

 Copy code hover
[image]

CustomXMLPart.SelectNodes Method (Office)
See also Send feedback

Published: July 09, 2012

Selects a collection of nodes from a custom XML part.

Syntax

expression .SelectNodes(XPath)

expression An expression that returns a CustomXMLPart object.

Parameters

Name | Required/Optional | Data Type | Description
XPath | Required | String | Contains the XPath expression.

Return Value

CustomXMLNodes

Example

The following example demonstrates adding a custom XML part, selecting a part matching a namespace URI, and then selecting nodes within that part that match an XPath expression.

VBA Copy code Copy code
Dim cxp1 As CustomXMLPart
Dim cxn As CustomXMLNode

' Add a custom xml part.
ActiveDocument.CustomXMLParts.Add "<supplier>"

' Return the first custom xml part with the given namespace.
Set cxp1 = ActiveDocument.CustomXMLParts("urn:invoice:namespace")

' Get all of the nodes matching an XPath expression.
 Set cxns = cxp1.SelectNodes("//*[@unitPrice > 20]")

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.SelectSingleNode Method (Office)

 Copy code hover
[image]

CustomXMLPart.SelectSingleNode Method (Office)
See also Send feedback

Published: July 09, 2012

Selects a single node within a custom XML part matching an XPath expression.

Syntax

expression .SelectSingleNode(XPath)

expression An expression that returns a CustomXMLPart object.

Parameters

Name | Required/Optional | Data Type | Description
XPath | Required | String | Contains an XPath expression.

Return Value

CustomXMLNode

Example

The following example demonstrates adding a custom XML part, selecting a part with a namespace URI, and then selecting a node within that part that matches an XPath expression.

VBA Copy code Copy code
Dim cxp1 As CustomXMLPart
Dim cxn As CustomXMLNode

' Add a custom XML part.
ActiveDocument.CustomXMLParts.Add ( _
    "<suppliers>" & _
    "<supplier ID='1'>Contoso</supplier>" & _
    "<supplier ID='2'>Wingtip Toys</supplier>" & _
    "</suppliers>")

' Return the last custom XML part added to the document.
Set cxp1 = ActiveDocument.CustomXMLParts(ActiveDocument.CustomXMLParts.Count)

' Get a node using XPath.
Set cxn = cxp1.SelectSingleNode("//supplier[@ID=1]")

' Display the node value 'Contoso'.
MsgBox cxn.NodeValue

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart Events (Office)

 Copy code hover
[image]

CustomXMLPart Events (Office)
Send feedback

Published: July 09, 2012

This object has the following events:

Events

Name | Description
NodeAfterDelete | Occurs after a node is deleted in a CustomXMLPart object.
NodeAfterInsert | Occurs after a node is inserted in a CustomXMLPart object.
NodeAfterReplace | Occurs just after a node is replaced in a CustomXMLPart object.


CustomXMLPart.NodeAfterDelete Event (Office)

 Copy code hover
[image]

CustomXMLPart.NodeAfterDelete Event (Office)
See also Send feedback

Published: July 09, 2012

Occurs after a node is deleted in a CustomXMLPart object.

Syntax

expression .NodeAfterDelete(OldNode, OldParentNode, OldNextSibling, InUndoRedo)

expression An expression that returns a CustomXMLPart object.

Parameters

Name | Required/Optional | Data Type | Description
OldNode | Required | CustomXMLNode | Corresponds to the node which was just removed from the CustomXMLPart object. Note that this node may have children, if a subtree is being removed from the document. Also, this node will be a "disconnected" node in that you can query down from the node, but you cannot query up the tree - the node appears to exist alone.
OldParentNode | Required | CustomXMLNode | Corresponds to the former parent node of OldNode.
OldNextSibling | Required | CustomXMLNode | Corresponds to the former next sibling of OldNode.
InUndoRedo | Required | Boolean | Returns TRUE if the node was inserted as part of an Undo/Redo action by the user.

Example

The following example displays a message telling the user the results of deleting the node.

VBA Copy code Copy code
Sub CustomXMLParts_NodeAfterDelete(newNode As CustomXMLNode, boolInUndoRedo As Boolean)
   MsgBox ("The node " & newNode.BaseName & " was just deleted.")
End Sub

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.NodeAfterInsert Event (Office)

 Copy code hover
[image]

CustomXMLPart.NodeAfterInsert Event (Office)
See also Send feedback

Published: July 09, 2012

Occurs after a node is inserted in a CustomXMLPart object.

Syntax

expression .NodeAfterInsert(NewNode, InUndoRedo)

expression An expression that returns a CustomXMLPart object.

Parameters

Name | Required/Optional | Data Type | Description
NewNode | Required | CustomXMLNode | Corresponds to the node just added to the CustomXMLPart object. Note that this node may have children, if a subtree was just added to the document.
InUndoRedo | Required | Boolean | Returns TRUE if the node was inserted as part of an Undo/Redo action by the user.

Example

The following example displays a message telling the user the results of inserting the node.

VBA Copy code Copy code
Sub CustomXMLParts_NodeAfterInsert(newNode As CustomXMLNode, boolInUndoRedo As Boolean)
   MsgBox ("The node " & newNode.BaseName & " was just inserted.")
End Sub

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLPart.NodeAfterReplace Event (Office)

 Copy code hover
[image]

CustomXMLPart.NodeAfterReplace Event (Office)
See also Send feedback

Published: July 09, 2012

Occurs just after a node is replaced in a CustomXMLPart object.

Syntax

expression .NodeAfterReplace(OldNode, NewNode, InUndoRedo)

expression An expression that returns a CustomXMLPart object.

Parameters

Name | Required/Optional | Data Type | Description
OldNode | Required | CustomXMLNode | Corresponds to the node which was just removed from the CustomXMLPart object. Note that this node may have children, if a subtree was just added to the document. Also, this node will be a "disconnected" node in that you can query down from the node, but cannot go up - it appears to exist alone.
NewNode | Required | CustomXMLNode | Corresponds to the node just added to the CustomXMLPart object.
InUndoRedo | Required | Boolean | Returns TRUE if the node was added as part of an Undo/Redo action by the user.

Example

The following example displays a message telling the user the results of replacing the node.

VBA Copy code Copy code
Sub CustomXMLParts_NodeAfterReplace(oldNode As CustomXMLNode, newNode As CustomXMLNode, boolInUndoRedo As Boolean)
   MsgBox ("The part's node " & oldNode.BaseName & " was replaced with the node " & newNode.BaseName)
End Sub

See also

Concepts

CustomXMLPart Object

Other resources

CustomXMLPart Object Members


CustomXMLParts Object (Office)

 Copy code hover
[image]

CustomXMLParts Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of CustomXMLPart objects.

Remarks

There are three default parts that are always created with a document. These are 'Cover pages', 'Doc properties' and 'App properties'. The last two were in previous versions of Microsoft Word but are now provided in XML form in the CustomXMLParts object collection

Example

The following example adds a node to a CustomXMLPart object that is part of the CustomXMLParts object collection.

VBA Copy code Copy code
Sub AddPartToCollection()
    Dim myPart As CustomXMLPart

    Set myPart = ActiveDocument.CustomXMLParts.Add("<author>Mark Twain</author>")

End Sub

See also

Concepts

Object Model Reference

Other resources

CustomXMLParts Object Members


CustomXMLParts Members (Office)

 Copy code hover
[image]

CustomXMLParts Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of CustomXMLPart objects.

Events

Name | Description
PartAfterAdd | Occurs just after a CustomXMLPart object is added to the CustomXMLParts collection.
PartAfterLoad | Occurs just after a CustomXMLPart object is loaded.
PartBeforeDelete | Occurs just before a CustomXMLPart object is deleted from the CustomXMLParts collection.

Methods

Name | Description
Add | Allows you to add a new CustomXMLPart to a file.
SelectByID | Selects a custom XML part matching a GUID.
SelectByNamespace | Selects the collection of custom XML parts whose namespace matches the search criteria.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLParts object. Read-only.
Count | Gets a Long indicating the number of items in the CustomXMLParts collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLParts object was created. Read-only.
Item | Gets a CustomXMLPart object from the CustomXMLParts collection. Read-only.
Parent | Gets the Parent object for the CustomXMLParts object. Read-only.


CustomXMLParts Properties (Office)

 Copy code hover
[image]

CustomXMLParts Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLParts object. Read-only.
Count | Gets a Long indicating the number of items in the CustomXMLParts collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLParts object was created. Read-only.
Item | Gets a CustomXMLPart object from the CustomXMLParts collection. Read-only.
Parent | Gets the Parent object for the CustomXMLParts object. Read-only.


CustomXMLParts.Application Property (Office)

 Copy code hover
[image]

CustomXMLParts.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the CustomXMLParts object. Read-only.

Syntax

expression .Application

expression An expression that returns a CustomXMLParts object.

Return Value

Object

See also

Concepts

CustomXMLParts Object

Other resources

CustomXMLParts Object Members


CustomXMLParts.Count Property (Office)

 Copy code hover
[image]

CustomXMLParts.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the CustomXMLParts collection. Read-only.

Syntax

expression .Count

expression An expression that returns a CustomXMLParts object.

Return Value

Long

See also

Concepts

CustomXMLParts Object

Other resources

CustomXMLParts Object Members


CustomXMLParts.Creator Property (Office)

 Copy code hover
[image]

CustomXMLParts.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CustomXMLParts object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a CustomXMLParts object.

Return Value

Long

See also

Concepts

CustomXMLParts Object

Other resources

CustomXMLParts Object Members


CustomXMLParts.Item Property (Office)

 Copy code hover
[image]

CustomXMLParts.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CustomXMLPart object from the CustomXMLParts collection. Read-only.

Syntax

expression .Item(Index)

expression An expression that returns a CustomXMLParts object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | The name or index number of the CustomXMLPart object to be returned.

Return Value

CustomXMLPart

See also

Concepts

CustomXMLParts Object

Other resources

CustomXMLParts Object Members


CustomXMLParts.Parent Property (Office)

 Copy code hover
[image]

CustomXMLParts.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CustomXMLParts object. Read-only.

Syntax

expression .Parent

expression An expression that returns a CustomXMLParts object.

Return Value

Object

See also

Concepts

CustomXMLParts Object

Other resources

CustomXMLParts Object Members


CustomXMLParts Methods (Office)

 Copy code hover
[image]

CustomXMLParts Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Allows you to add a new CustomXMLPart to a file.
SelectByID | Selects a custom XML part matching a GUID.
SelectByNamespace | Selects the collection of custom XML parts whose namespace matches the search criteria.


CustomXMLParts.Add Method (Office)

 Copy code hover
[image]

CustomXMLParts.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Allows you to add a new CustomXMLPart to a file.

Syntax

expression .Add(XML, SchemaCollection)

expression An expression that returns a CustomXMLParts object.

Parameters

Name | Required/Optional | Data Type | Description
XML | Optional | String | Contains the XML to add to the newly created CustomXMLPart.
SchemaCollection | Optional | CustomXMLSchemaCollection | Represents the set of schemas to be used to validate this stream.

Return Value

CustomXMLPart

Example

The following example adds a new CustomXMLPart, selects a CustomXMLPart using a search criteria, and then selects a single node from that part.

VBA Copy code Copy code
Sub ShowCustomXmlParts()
    On Error GoTo Err

    Dim cxp1 As CustomXMLPart

    Dim cxn As CustomXMLNode
    Dim cxns As CustomXMLNodes
    Dim strXml As String
    Dim strUri As String

        ' Example written for Word.

        ' Add a custom XML part.
        ActiveDocument.CustomXMLParts.Add "<custXMLPart />"

        ' Returns the first custom XML part with the given root namespace.
        Set cxp1 = ActiveDocument.CustomXMLParts("urn:invoice:namespace")

        ' Get a node using XPath.
        Set cxn = cxp1.SelectSingleNode("//*[@quantity < 4]")

    Exit Sub

' Exception handling. Show the message and resume.
Err:
        MsgBox (Err.Description)
        Resume Next
End Sub

See also

Concepts

CustomXMLParts Object

Other resources

CustomXMLParts Object Members


CustomXMLParts.SelectByID Method (Office)

 Copy code hover
[image]

CustomXMLParts.SelectByID Method (Office)
See also Send feedback

Published: July 09, 2012

Selects a custom XML part matching a GUID.

Syntax

expression .SelectByID(Id)

expression An expression that returns a CustomXMLParts object.

Parameters

Name | Required/Optional | Data Type | Description
Id | Required | String | Contains the GUID for the custom XML part.

Return Value

CustomXMLPart

Remarks

If a custom XML part with this ID does not exist, the method returns Nothing.

Example

The following example retrieves a custom XML part matching the GUID and then searches for a node in that part that matches an XPath expression.

VBA Copy code Copy code
Dim cxp1 As CustomXMLPart
Dim cxn As CustomXMLNode

' Returns a custom xml part by its ID.
 Set cxp1 = ActiveDocument.CustomXMLParts.SelectByID("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4")

' Get the node matching the XPath expression.
Set cxn = cxp1.SelectSingleNode("//*[@supplierID = 1]")

See also

Concepts

CustomXMLParts Object

Other resources

CustomXMLParts Object Members


CustomXMLParts.SelectByNamespace Method (Office)

 Copy code hover
[image]

CustomXMLParts.SelectByNamespace Method (Office)
See also Send feedback

Published: July 09, 2012

Selects the collection of custom XML parts whose namespace matches the search criteria.

Syntax

expression .SelectByNamespace(NamespaceURI)

expression An expression that returns a CustomXMLParts object.

Parameters

Name | Required/Optional | Data Type | Description
NamespaceURI | Required | String | Contains a namespace URI.

Return Value

CustomXMLParts

Remarks

If no custom XML parts with this namespace exist, the method returns an empty CustomXMLParts collection object.

Example

The following example selects all of the custom XML parts matching the namespace and then selects a node from those parts that match an XPath expression.

VBA Copy code Copy code
Dim cxp1 As CustomXMLParts
Dim cxn As CustomXMLNode

' Returns all of the custom xml parts with the given namespace.
 Set cxp1 = ActiveDocument.CustomXMLParts.SelectByNamespace("urn:invoice:namespace")

' Get the node matching the XPath expression.
Set cxn = cxp1(1).SelectSingleNode("//*[@supplierID = 1]")

See also

Concepts

CustomXMLParts Object

Other resources

CustomXMLParts Object Members


CustomXMLParts Events (Office)

 Copy code hover
[image]

CustomXMLParts Events (Office)
Send feedback

Published: July 09, 2012

This object has the following events:

Events

Name | Description
PartAfterAdd | Occurs just after a CustomXMLPart object is added to the CustomXMLParts collection.
PartAfterLoad | Occurs just after a CustomXMLPart object is loaded.
PartBeforeDelete | Occurs just before a CustomXMLPart object is deleted from the CustomXMLParts collection.


CustomXMLParts.PartAfterAdd Event (Office)

 Copy code hover
[image]

CustomXMLParts.PartAfterAdd Event (Office)
See also Send feedback

Published: July 09, 2012

Occurs just after a CustomXMLPart object is added to the CustomXMLParts collection.

Syntax

expression .PartAfterAdd(NewPart, )

An expression that returns a CustomXMLParts object.

Parameters

Name | Required/Optional | Data Type | Description
NewPart | Required | CustomXMLPart | The part that was added.

Example

The following example displays the XML contents of a part after it has been added to a CustomXMLParts collection.

VBA Copy code Copy code
Sub CustomXMLParts_PartAfterAdd(ByVal objPart As CustomXMLPart)
Dim strPartXML As String
strPartXML = objPart.XML
   MsgBox ("The part's contents are: " & vbCrLf & strPartXML)
End Sub

See also

Concepts

CustomXMLParts Object

Other resources

CustomXMLParts Object Members


CustomXMLParts.PartAfterLoad Event (Office)

 Copy code hover
[image]

CustomXMLParts.PartAfterLoad Event (Office)
See also Send feedback

Occurs just after a CustomXMLPart object is loaded.

Syntax

expression .PartAfterLoad(Part, )

expression An expression that returns a CustomXMLParts object.

Parameters

Name | Required/Optional | Data Type | Description
Part | Required | CustomXMLPart | The part that was loaded.

Example

The following example adds XML to a part after it is loaded.

VBA Copy code Copy code
Sub CustomXMLParts_PartAfterLoad(ByVal objPart As CustomXMLPart)
   objPart.XML ("<root xmlns='http://www.w3c.org/XMLSchema'>text</root>")
End Sub

See also

Concepts

CustomXMLParts Object

Other resources

CustomXMLParts Object Members


CustomXMLParts.PartBeforeDelete Event (Office)

 Copy code hover
[image]

CustomXMLParts.PartBeforeDelete Event (Office)
See also Send feedback

Published: July 09, 2012

Occurs just before a CustomXMLPart object is deleted from the CustomXMLParts collection.

Syntax

expression .PartBeforeDelete(OldPart, )

expression An expression that returns a CustomXMLParts object.

Parameters

Name | Required/Optional | Data Type | Description
OldPart | Required | CustomXMLPart | The part that is about to be deleted.

Example

The following example confirms that the user wants to delete the customXML part and then deletes the part if the user clicks Yes in the dialog box.

VBA Copy code Copy code
Sub CustomXMLParts_PartBeforeDelete(ByVal oldPart As CustomXMLPart)
Dim result As Boolean

result = MsgBox("Are you sure you want to delete the " & oldPart.ID & " part?", vbYesNo)

If result Then
   oldPart.Delete
End If

End Sub

See also

Concepts

CustomXMLParts Object

Other resources

CustomXMLParts Object Members


CustomXMLPrefixMapping Object (Office)

 Copy code hover
[image]

CustomXMLPrefixMapping Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a namespace prefix.

Example

The following example creates a CustomXMLPrefixMapping object by adding a namespace and prefix to the CustomXMLPrefixMapping collection.

VBA Copy code Copy code
Dim objNamespace As CustomXMLPrefixMapping

objNamespace = CustomXMLPrefixMappings.AddNamespace("xs", "urn:invoice:namespace")

See also

Concepts

Object Model Reference

Other resources

CustomXMLPrefixMapping Object Members


CustomXMLPrefixMapping Members (Office)

 Copy code hover
[image]

CustomXMLPrefixMapping Members (Office)
Send feedback

Published: July 09, 2012

Represents a namespace prefix.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLPrefixMapping object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLPrefixMapping object was created. Read-only.
NamespaceURI | Gets the unique address identifier for the namespace of the CustomXMLPrefixMapping object. Read-only.
Parent | Gets the Parent object of the CustomXMLPrefixMapping object. Read-only.
Prefix | Gets the prefix for a CustomXMLPrefixMapping object. Read-only.


CustomXMLPrefixMapping Properties (Office)

 Copy code hover
[image]

CustomXMLPrefixMapping Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLPrefixMapping object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLPrefixMapping object was created. Read-only.
NamespaceURI | Gets the unique address identifier for the namespace of the CustomXMLPrefixMapping object. Read-only.
Parent | Gets the Parent object of the CustomXMLPrefixMapping object. Read-only.
Prefix | Gets the prefix for a CustomXMLPrefixMapping object. Read-only.


CustomXMLPrefixMapping.Application Property (Office)

 Copy code hover
[image]

CustomXMLPrefixMapping.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the CustomXMLPrefixMapping object. Read-only.

Syntax

expression .Application

expression An expression that returns a CustomXMLPrefixMapping object.

Return Value

Object

See also

Concepts

CustomXMLPrefixMapping Object

Other resources

CustomXMLPrefixMapping Object Members


CustomXMLPrefixMapping.Creator Property (Office)

 Copy code hover
[image]

CustomXMLPrefixMapping.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CustomXMLPrefixMapping object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a CustomXMLPrefixMapping object.

Return Value

Long

See also

Concepts

CustomXMLPrefixMapping Object

Other resources

CustomXMLPrefixMapping Object Members


CustomXMLPrefixMapping.NamespaceURI Property (Office)

 Copy code hover
[image]

CustomXMLPrefixMapping.NamespaceURI Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the unique address identifier for the namespace of the CustomXMLPrefixMapping object. Read-only.

Syntax

expression .NamespaceURI

expression An expression that returns a CustomXMLPrefixMapping object.

Return Value

String

See also

Concepts

CustomXMLPrefixMapping Object

Other resources

CustomXMLPrefixMapping Object Members


CustomXMLPrefixMapping.Parent Property (Office)

 Copy code hover
[image]

CustomXMLPrefixMapping.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object of the CustomXMLPrefixMapping object. Read-only.

Syntax

expression .Parent

expression An expression that returns a CustomXMLPrefixMapping object.

Return Value

Object

See also

Concepts

CustomXMLPrefixMapping Object

Other resources

CustomXMLPrefixMapping Object Members


CustomXMLPrefixMapping.Prefix Property (Office)

 Copy code hover
[image]

CustomXMLPrefixMapping.Prefix Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the prefix for a CustomXMLPrefixMapping object. Read-only.

Syntax

expression .Prefix

expression An expression that returns a CustomXMLPrefixMapping object.

Return Value

String

See also

Concepts

CustomXMLPrefixMapping Object

Other resources

CustomXMLPrefixMapping Object Members


CustomXMLPrefixMappings Object (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of CustomXMLPrefixMapping objects.

Example

The following example creates a CustomXMLPrefixMapping object by adding a namespace and prefix to the CustomXMLPrefixMapping collection.

VBA Copy code Copy code
Dim objNamespace As CustomXMLPrefixMapping

objNamespace = CustomXMLPrefixMappings.AddNamespace("xs", "urn:invoice:namespace")

See also

Concepts

Object Model Reference

Other resources

CustomXMLPrefixMappings Object Members


CustomXMLPrefixMappings Members (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of CustomXMLPrefixMapping objects.

Methods

Name | Description
AddNamespace | Allows you to add a custom namespace/prefix mapping to use when querying an item.
LookupNamespace | Allows you to get the namespace corresponding to the specified prefix.
LookupPrefix | Allows you to get a prefix corresponding to the specified namespace.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLPrefixMappings object. Read-only.
Count | Gets a Long indicating the number of items in the CustomXMLPrefixMappings collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLPrefixMappings object was created. Read-only.
Item | Gets a CustomXMLPrefixMapping object from the CustomXMLPrefixMappings collection. Read-only.
Parent | Gets the Parent object for the CustomXMLPrefixMappings object. Read-only.


CustomXMLPrefixMappings Properties (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLPrefixMappings object. Read-only.
Count | Gets a Long indicating the number of items in the CustomXMLPrefixMappings collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLPrefixMappings object was created. Read-only.
Item | Gets a CustomXMLPrefixMapping object from the CustomXMLPrefixMappings collection. Read-only.
Parent | Gets the Parent object for the CustomXMLPrefixMappings object. Read-only.


CustomXMLPrefixMappings.Application Property (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the CustomXMLPrefixMappings object. Read-only.

Syntax

expression .Application

expression An expression that returns a CustomXMLPrefixMappings object.

Return Value

Object

See also

Concepts

CustomXMLPrefixMappings Object

Other resources

CustomXMLPrefixMappings Object Members


CustomXMLPrefixMappings.Count Property (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the CustomXMLPrefixMappings collection. Read-only.

Syntax

expression .Count

expression An expression that returns a CustomXMLPrefixMappings object.

Return Value

Long

See also

Concepts

CustomXMLPrefixMappings Object

Other resources

CustomXMLPrefixMappings Object Members


CustomXMLPrefixMappings.Creator Property (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CustomXMLPrefixMappings object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a CustomXMLPrefixMappings object.

Return Value

Long

See also

Concepts

CustomXMLPrefixMappings Object

Other resources

CustomXMLPrefixMappings Object Members


CustomXMLPrefixMappings.Item Property (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CustomXMLPrefixMapping object from the CustomXMLPrefixMappings collection. Read-only.

Syntax

expression .Item(Index)

expression An expression that returns a CustomXMLPrefixMappings object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | The name or index number of the CustomXMLPrefixMapping object to be returned.

Return Value

CustomXMLPrefixMapping

See also

Concepts

CustomXMLPrefixMappings Object

Other resources

CustomXMLPrefixMappings Object Members


CustomXMLPrefixMappings.Parent Property (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CustomXMLPrefixMappings object. Read-only.

Syntax

expression .Parent

expression An expression that returns a CustomXMLPrefixMappings object.

Return Value

Object

See also

Concepts

CustomXMLPrefixMappings Object

Other resources

CustomXMLPrefixMappings Object Members


CustomXMLPrefixMappings Methods (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
AddNamespace | Allows you to add a custom namespace/prefix mapping to use when querying an item.
LookupNamespace | Allows you to get the namespace corresponding to the specified prefix.
LookupPrefix | Allows you to get a prefix corresponding to the specified namespace.


CustomXMLPrefixMappings.AddNamespace Method (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings.AddNamespace Method (Office)
See also Send feedback

Published: July 09, 2012

Allows you to add a custom namespace/prefix mapping to use when querying an item.

Syntax

expression .AddNamespace(Prefix, NamespaceURI)

expression An expression that returns a CustomXMLPrefixMappings object.

Parameters

Name | Required/Optional | Data Type | Description
Prefix | Required | String | Contains the prefix to add to the prefix mapping list.
NamespaceURI | Required | String | Contains the namespace to assign to the newly added prefix.

Remarks

If the prefix already exists in the Namespace Manager, this method will overwrite the meaning of that prefix except when the prefix is one added or used by the data store (IXMLDataStore interface) internally, in which case it will return an error.

Example

The following example adds a prefix and namespace to a CustomPrefixMappings object.

VBA Copy code Copy code
Sub AddNamespacePrefix()

    Dim objCustomPrefixMappings As  CustomPrefixMappings
    Dim varCustomMapping As Variant

    ' Adds a custom namespace.
    varCustomMapping = objCustomPrefixMappings.AddNamespace("xs", "urn:invoice:namespace")

End Sub

See also

Concepts

CustomXMLPrefixMappings Object

Other resources

CustomXMLPrefixMappings Object Members


CustomXMLPrefixMappings.LookupNamespace Method (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings.LookupNamespace Method (Office)
See also Send feedback

Published: July 09, 2012

Allows you to get the namespace corresponding to the specified prefix.

Syntax

expression .LookupNamespace(Prefix)

expression An expression that returns a CustomXMLPrefixMappings object.

Parameters

Name | Required/Optional | Data Type | Description
Prefix | Required | String | Contains a prefix in the prefix mapping list.

Return Value

String

Remarks

If no namespace is assigned to the requested prefix, the method returns an empty string ("").

Example

The following example retrieves the namespace corresponding to the prefix argument.

VBA Copy code Copy code
Dim objCustomPrefixMappings As  CustomPrefixMappings
    Dim strNamespace As String

    ' Gets the namespace corresponding to the prefix.
   strNamespace = objCustomPrefixMappings.LookupNamespace("xs")

See also

Concepts

CustomXMLPrefixMappings Object

Other resources

CustomXMLPrefixMappings Object Members


CustomXMLPrefixMappings.LookupPrefix Method (Office)

 Copy code hover
[image]

CustomXMLPrefixMappings.LookupPrefix Method (Office)
See also Send feedback

Published: July 09, 2012

Allows you to get a prefix corresponding to the specified namespace.

Syntax

expression .LookupPrefix(NamespaceURI)

expression An expression that returns a CustomXMLPrefixMappings object.

Parameters

Name | Required/Optional | Data Type | Description
NamespaceURI | Required | String | Contains the namespace URI.

Return Value

String

Remarks

If no prefix is assigned to the requested namespace, the method returns an empty string (""). If there are multiple prefixes specified in the namespace manager, the method returns the first prefix that matches the supplied namespace.

Example

The following example retrieves the namespace prefix associated with the namespace URI.

VBA Copy code Copy code
Dim objCustomPrefixMappings As  CustomPrefixMappings
Dim strNamespacePrefix As String

' Gets the namespace corresponding to the prefix.
strNamespacePrefix = objCustomPrefixMappings.LookupPrefix("urn:invoice:namespace")

See also

Concepts

CustomXMLPrefixMappings Object

Other resources

CustomXMLPrefixMappings Object Members


CustomXMLSchema Object (Office)

 Copy code hover
[image]

CustomXMLSchema Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a schema in a CustomXMLSchemaCollection collection.

Example

The following example adds a CustomXMLSchema object to a CustomXMLSchemaCollection object.

VBA Copy code Copy code
Dim SchemaCollection As CustomXMLSchemaCollection

SchemaCollection.Add "http://tempuri.org/XMLSchema.xsd"

See also

Concepts

Object Model Reference

Other resources

CustomXMLSchema Object Members


CustomXMLSchema Members (Office)

 Copy code hover
[image]

CustomXMLSchema Members (Office)
Send feedback

Published: July 09, 2012

Represents a schema in a CustomXMLSchemaCollection collection.

Methods

Name | Description
Delete | Deletes the specified schema from the CustomXMLSchema collection.
Reload | Reloads a schema from a file.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLSchema object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLSchema object was created. Read-only.
Location | Gets a String that represents the location of a schema on a computer. Read-only.
NamespaceURI | Gets the unique address identifier for the namespace of the CustomXMLSchema object. Read-only.
Parent | Gets the Parent object for the CustomXMLSchema object. Read-only.


CustomXMLSchema Properties (Office)

 Copy code hover
[image]

CustomXMLSchema Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLSchema object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLSchema object was created. Read-only.
Location | Gets a String that represents the location of a schema on a computer. Read-only.
NamespaceURI | Gets the unique address identifier for the namespace of the CustomXMLSchema object. Read-only.
Parent | Gets the Parent object for the CustomXMLSchema object. Read-only.


CustomXMLSchema.Application Property (Office)

 Copy code hover
[image]

CustomXMLSchema.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the CustomXMLSchema object. Read-only.

Syntax

expression .Application

expression An expression that returns a CustomXMLSchema object.

Return Value

Object

See also

Concepts

CustomXMLSchema Object

Other resources

CustomXMLSchema Object Members


CustomXMLSchema.Creator Property (Office)

 Copy code hover
[image]

CustomXMLSchema.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CustomXMLSchema object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a CustomXMLSchema object.

Return Value

Long

See also

Concepts

CustomXMLSchema Object

Other resources

CustomXMLSchema Object Members


CustomXMLSchema.Location Property (Office)

 Copy code hover
[image]

CustomXMLSchema.Location Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a String that represents the location of a schema on a computer. Read-only.

Syntax

expression .Location

expression An expression that returns a CustomXMLSchema object.

Return Value

String

See also

Concepts

CustomXMLSchema Object

Other resources

CustomXMLSchema Object Members


CustomXMLSchema.NamespaceURI Property (Office)

 Copy code hover
[image]

CustomXMLSchema.NamespaceURI Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the unique address identifier for the namespace of the CustomXMLSchema object. Read-only.

Syntax

expression .NamespaceURI

expression An expression that returns a CustomXMLSchema object.

Return Value

String

See also

Concepts

CustomXMLSchema Object

Other resources

CustomXMLSchema Object Members


CustomXMLSchema.Parent Property (Office)

 Copy code hover
[image]

CustomXMLSchema.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CustomXMLSchema object. Read-only.

Syntax

expression .Parent

expression An expression that returns a CustomXMLSchema object.

Return Value

Object

See also

Concepts

CustomXMLSchema Object

Other resources

CustomXMLSchema Object Members


CustomXMLSchema Methods (Office)

 Copy code hover
[image]

CustomXMLSchema Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes the specified schema from the CustomXMLSchema collection.
Reload | Reloads a schema from a file.


CustomXMLSchema.Delete Method (Office)

 Copy code hover
[image]

CustomXMLSchema.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the specified schema from the CustomXMLSchema collection.

Syntax

expression .Delete

expression An expression that returns a CustomXMLSchema object.

Remarks

If this operation is attempted on a schema in a collection that is already validated or attached to a data stream, then the operation is not performed and an error message is displayed.

Example

The following example adds a schema to the collection and then deletes the schema.

VBA Copy code Copy code
Sub DeleteSchema()
    On Error GoTo Err

    Dim objCustomXMLSchemaCollection As CustomXMLSchemaCollection
    Dim objCustomXMLSchema As  CustomXMLSchema

    ' Adds a schema to the collection.
    objCustomXMLSchema.Add("urn:invoice:namespace")

    ...

    ' Deletes the schema.
    objCustomXMLSchema.Delete

    Exit Sub

' Exception handling. Show the message and resume.
Err:
        MsgBox (Err.Description)
        Resume Next
End Sub

See also

Concepts

CustomXMLSchema Object

Other resources

CustomXMLSchema Object Members


CustomXMLSchema.Reload Method (Office)

 Copy code hover
[image]

CustomXMLSchema.Reload Method (Office)
See also Send feedback

Published: July 09, 2012

Reloads a schema from a file.

Syntax

expression .Reload

expression An expression that returns a CustomXMLSchema object.

Remarks

Typically, this method is used to update the location of the schema or to determine if the schema is still valid. It is also useful for reloading a schema that frequently changes. If this action is attempted on a schema in a collection that is already validated or tied to a data stream, then the operation is not performed and an error message is displayed.

Example

The following example specifies the location of the schema and then reloads it.

VBA Copy code Copy code
Dim objCustomXMLSchema As  CustomXMLSchema
Dim strSchemaLocation As String
' Set the location of the schema..
objCustomXMLSchema.Location = "c:\mySchema.xsd"

' Reload the schema.
objCustomXMLSchema.Reload

See also

Concepts

CustomXMLSchema Object

Other resources

CustomXMLSchema Object Members


CustomXMLSchemaCollection Object (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of CustomXMLSchema objects attached to a data stream.

Example

The following example adds a CustomXMLSchema object to a CustomXMLSchemaCollection object.

VBA Copy code Copy code
Dim SchemaCollection As CustomXMLSchemaCollection

SchemaCollection.Add "http://tempuri.org/XMLSchema.xsd"

See also

Concepts

Object Model Reference

Other resources

CustomXMLSchemaCollection Object Members


CustomXMLSchemaCollection Members (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of CustomXMLSchema objects attached to a data stream.

Methods

Name | Description
Add | Allows you to add one or more schemas to a schema collection that can then be added to a stream in the data store and to the Schema Library.
AddCollection | Adds an existing schema collection to the current schema collection.
Validate | Specifies whether the schemas in a schema collection are valid (conforms to the syntactic rules of XML and the rules for a specified vocabulary; a standard for structuring XML).

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLSchemaCollection object. Read-only.
Count | Gets a Long indicating the number of items in the CustomXMLSchemaCollection collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLSchemaCollection object was created. Read-only.
Item | Gets a CustomXMLSchema object from the CustomXMLSchemaCollection collection. Read-only.
NamespaceURI | Gets the unique address identifier for the namespace of the CustomXMLSchemaCollection object. Read-only.
Parent | Gets the Parent object for the CustomXMLSchemaCollection object. Read-only.


CustomXMLSchemaCollection Properties (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLSchemaCollection object. Read-only.
Count | Gets a Long indicating the number of items in the CustomXMLSchemaCollection collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLSchemaCollection object was created. Read-only.
Item | Gets a CustomXMLSchema object from the CustomXMLSchemaCollection collection. Read-only.
NamespaceURI | Gets the unique address identifier for the namespace of the CustomXMLSchemaCollection object. Read-only.
Parent | Gets the Parent object for the CustomXMLSchemaCollection object. Read-only.


CustomXMLSchemaCollection.Application Property (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the CustomXMLSchemaCollection object. Read-only.

Syntax

expression .Application

expression An expression that returns a CustomXMLSchemaCollection object.

Return Value

Object

See also

Concepts

CustomXMLSchemaCollection Object

Other resources

CustomXMLSchemaCollection Object Members


CustomXMLSchemaCollection.Count Property (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the CustomXMLSchemaCollection collection. Read-only.

Syntax

expression .Count

expression An expression that returns a CustomXMLSchemaCollection object.

Return Value

Long

See also

Concepts

CustomXMLSchemaCollection Object

Other resources

CustomXMLSchemaCollection Object Members


CustomXMLSchemaCollection.Creator Property (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CustomXMLSchemaCollection object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a CustomXMLSchemaCollection object.

Return Value

Long

See also

Concepts

CustomXMLSchemaCollection Object

Other resources

CustomXMLSchemaCollection Object Members


CustomXMLSchemaCollection.Item Property (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CustomXMLSchema object from the CustomXMLSchemaCollection collection. Read-only.

Syntax

expression .Item(Index)

expression An expression that returns a CustomXMLSchemaCollection object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | The name or index number of the CustomXMLSchema object to be returned.

Return Value

CustomXMLSchema

See also

Concepts

CustomXMLSchemaCollection Object

Other resources

CustomXMLSchemaCollection Object Members


CustomXMLSchemaCollection.NamespaceURI Property (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection.NamespaceURI Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the unique address identifier for the namespace of the CustomXMLSchemaCollection object. Read-only.

Syntax

expression .NamespaceURI(Index)

expression An expression that returns a CustomXMLSchemaCollection object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | The index number of the CustomXMLSchema object.

Return Value

String

See also

Concepts

CustomXMLSchemaCollection Object

Other resources

CustomXMLSchemaCollection Object Members


CustomXMLSchemaCollection.Parent Property (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CustomXMLSchemaCollection object. Read-only.

Syntax

expression .Parent

expression An expression that returns a CustomXMLSchemaCollection object.

Return Value

Object

See also

Concepts

CustomXMLSchemaCollection Object

Other resources

CustomXMLSchemaCollection Object Members


CustomXMLSchemaCollection Methods (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Allows you to add one or more schemas to a schema collection that can then be added to a stream in the data store and to the Schema Library.
AddCollection | Adds an existing schema collection to the current schema collection.
Validate | Specifies whether the schemas in a schema collection are valid (conforms to the syntactic rules of XML and the rules for a specified vocabulary; a standard for structuring XML).


CustomXMLSchemaCollection.Add Method (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Allows you to add one or more schemas to a schema collection that can then be added to a stream in the data store and to the Schema Library.

Syntax

expression .Add(NamespaceURI, Alias, FileName, InstallForAllUsers)

expression An expression that returns a CustomXMLSchemaCollection object.

Parameters

Name | Required/Optional | Data Type | Description
NamespaceURI | Optional | String | Contains the namespace of the schema to be added to the collection. If the schema already exists in the Schema Library, the method will retrieve it from there.
Alias | Optional | String | Contains the alias of the schema to be added to the collection. If the alias already exists in the Schema Library, the method can find it using this argument.
FileName | Optional | String | Contains the location of the schema on a disk. If this parameter is specified, the schema is added to the collection and to to the Schema Library.
InstallForAllUsers | Optional | Boolean | Specifies whether, in the case where the method is adding the schema to the Schema Library, the Schema Library keys should be written to the registry(HKey_Local_Machine for all users or HKey_Current_User for just the current user). The parameter defaults to False and writes to HKey_Current_User.

Return Value

CustomXMLSchema

Example

The following example adds a schema to the schema collection, selects a single node from it, and then returns the node to the calling procedure.

VBA Copy code Copy code
Function AddSchema()
    On Error GoTo Err

    Dim objCustomXMLSchemaCollection As CustomXMLSchemaCollection
    Dim cxp1 As  CustomXMLSchema
    Dim cxn As CustomXMLNode

    ' Adds a schema to the collection.
    cxp1 = objCustomXMLSchemaCollection.Add("urn:invoice:namespace", "coreDefinitions", wdCore.xsd", True)

...

    Set cxn = cxp4.SelectSingleNode("//*[@quantity < 4]")

    AddSchema = cxn

    Exit Function

' Exception handling. Show the message and resume.
Err:
        MsgBox (Err.Description)
        Resume Next
End Function

See also

Concepts

CustomXMLSchemaCollection Object

Other resources

CustomXMLSchemaCollection Object Members


CustomXMLSchemaCollection.AddCollection Method (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection.AddCollection Method (Office)
See also Send feedback

Published: July 09, 2012

Adds an existing schema collection to the current schema collection.

Syntax

expression .AddCollection(SchemaCollection)

expression An expression that returns a CustomXMLSchemaCollection object.

Parameters

Name | Required/Optional | Data Type | Description
SchemaCollection | Required | CustomXMLSchemaCollection | Represents a collection of schemas to be imported into the current schema collection.

Remarks

If there is a conflict between namespaces while importing the collection, for example if x.xsd is already linked to "urn:invoice:namespace" but the incoming collection has z.xsd for the same namespace, the incoming collection wins.

Example

The following example receives the target schema collection and incoming schema collection arguments and then adds the one collection to the other.

VBA Copy code Copy code
Sub AddSchema(objTargetCustomXMLSchemaCollection As CustomXMLSchemaCollection, _
  objTargetCustomXMLSchemaCollection As CustomXMLSchemaCollection)

    ' Adds a schema collection to another schema the collection.
    objTargetCustomXMLSchemaCollection.AddCollection(objIncomingCustomXMLSchemaCollection)

End Sub

See also

Concepts

CustomXMLSchemaCollection Object

Other resources

CustomXMLSchemaCollection Object Members


CustomXMLSchemaCollection.Validate Method (Office)

 Copy code hover
[image]

CustomXMLSchemaCollection.Validate Method (Office)
See also Send feedback

Published: July 09, 2012

Specifies whether the schemas in a schema collection are valid (conforms to the syntactic rules of XML and the rules for a specified vocabulary; a standard for structuring XML).

Syntax

expression .Validate

expression An expression that returns a CustomXMLSchemaCollection object.

Return Value

Boolean

Remarks

In addition to determining whether the schemas are valid, this method also traverses the include statements for each schema in the collection and adds the referenced schemas to the source schema.

Example

The following example validates the schema collection and returns the Boolean results to the calling procedure.

VBA Copy code Copy code
Function ValidateSchemas(objSourceCustomXMLSchemaCollection As CustomXMLSchemaCollection)
Dim boolValid As Boolean

' Validates the schemas in a schema collection.
boolValid = objSourceCustomXMLSchemaCollection.Validate

ValidateSchemas = boolValid

End Function

See also

Concepts

CustomXMLSchemaCollection Object

Other resources

CustomXMLSchemaCollection Object Members


CustomXMLValidationError Object (Office)

 Copy code hover
[image]

CustomXMLValidationError Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a single validation error in a CustomXMLValidationErrors collection.

Remarks

Validation errors can either be triggered when validating an operation against the schema, such as when adding a node, or triggered by the user when some condition is not met. For example, if a start date is later than an end date.

Example

The following example adds a custom part and then adds a child node to that part. Any errors that occur are added to the CustomXMLValidationErrors collection and then displayed in the Debug window.

VBA Copy code Copy code
Dim ValErrors As CustomXMLValidationErrors
Dim ValError As CustomXMLValidationError
Dim cxp1 As CustomXMLPart
Dim intError As Integer

On Error Go To validation_error

 With ActiveDocument

    ' Add and populate a custom xml part
    set cxp1 = .CustomXMLParts.Add "<invoice>"

    ' Add a node
    cxp1.AddNode "<quantity>", "supplier", "urn:invoice:namespace"

 End With

If ValErrors.Count > 0 then
   For Each ValError In ValErrors
      DeBug.Print("Error name: " & ValError.Name & " Error description: " & ValError.Text)
   Next
End If

Exit Sub

validation_error:
   CustomXMLValidationErrors.Add(ValError.Name, ValError.Text))
Resume

See also

Concepts

Object Model Reference

Other resources

CustomXMLValidationError Object Members


CustomXMLValidationError Members (Office)

 Copy code hover
[image]

CustomXMLValidationError Members (Office)
Send feedback

Published: July 09, 2012

Represents a single validation error in a CustomXMLValidationErrors collection.

Methods

Name | Description
Delete | Deletes the CustomXMLValidationError object representing a data validation error.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLValidationError object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLValidationError object was created. Read-only.
ErrorCode | Gets a number representing a validation error in a CustomXMLValidationError object. Read-only.
Name | Gets the name of an error in a CustomXMLValidationError object. If no errors exist, the property returns Nothing. Read-only.
Node | Gets a node in a CustomXMLValidationError object, if any exist. If no nodes exist, the property returns Nothing. Read-only.
Parent | Gets the Parent object for the CustomXMLValidationError object. Read-only.
Text | Gets the text in the CustomXMLValidationError object. Read-only.
Type | Gets the type of error generated from the CustomXMLValidationError object. Read-only.


CustomXMLValidationError Properties (Office)

 Copy code hover
[image]

CustomXMLValidationError Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLValidationError object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLValidationError object was created. Read-only.
ErrorCode | Gets a number representing a validation error in a CustomXMLValidationError object. Read-only.
Name | Gets the name of an error in a CustomXMLValidationError object. If no errors exist, the property returns Nothing. Read-only.
Node | Gets a node in a CustomXMLValidationError object, if any exist. If no nodes exist, the property returns Nothing. Read-only.
Parent | Gets the Parent object for the CustomXMLValidationError object. Read-only.
Text | Gets the text in the CustomXMLValidationError object. Read-only.
Type | Gets the type of error generated from the CustomXMLValidationError object. Read-only.


CustomXMLValidationError.Application Property (Office)

 Copy code hover
[image]

CustomXMLValidationError.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the CustomXMLValidationError object. Read-only.

Syntax

expression .Application

expression An expression that returns a CustomXMLValidationError object.

Return Value

Object

See also

Concepts

CustomXMLValidationError Object

Other resources

CustomXMLValidationError Object Members


CustomXMLValidationError.Creator Property (Office)

 Copy code hover
[image]

CustomXMLValidationError.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CustomXMLValidationError object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a CustomXMLValidationError object.

Return Value

Long

See also

Concepts

CustomXMLValidationError Object

Other resources

CustomXMLValidationError Object Members


CustomXMLValidationError.ErrorCode Property (Office)

 Copy code hover
[image]

CustomXMLValidationError.ErrorCode Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a number representing a validation error in a CustomXMLValidationError object. Read-only.

Syntax

expression .ErrorCode

expression An expression that returns a CustomXMLValidationError object.

Return Value

Long

See also

Concepts

CustomXMLValidationError Object

Other resources

CustomXMLValidationError Object Members


CustomXMLValidationError.Name Property (Office)

 Copy code hover
[image]

CustomXMLValidationError.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of an error in a CustomXMLValidationError object. If no errors exist, the property returns Nothing. Read-only.

Syntax

expression .Name

expression An expression that returns a CustomXMLValidationError object.

Return Value

String

See also

Concepts

CustomXMLValidationError Object

Other resources

CustomXMLValidationError Object Members


CustomXMLValidationError.Node Property (Office)

 Copy code hover
[image]

CustomXMLValidationError.Node Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a node in a CustomXMLValidationError object, if any exist. If no nodes exist, the property returns Nothing. Read-only.

Syntax

expression .Node

expression An expression that returns a CustomXMLValidationError object.

Return Value

CustomXMLNode

See also

Concepts

CustomXMLValidationError Object

Other resources

CustomXMLValidationError Object Members


CustomXMLValidationError.Parent Property (Office)

 Copy code hover
[image]

CustomXMLValidationError.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CustomXMLValidationError object. Read-only.

Syntax

expression .Parent

expression An expression that returns a CustomXMLValidationError object.

Return Value

Object

See also

Concepts

CustomXMLValidationError Object

Other resources

CustomXMLValidationError Object Members


CustomXMLValidationError.Text Property (Office)

 Copy code hover
[image]

CustomXMLValidationError.Text Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the text in the CustomXMLValidationError object. Read-only.

Syntax

expression .Text

expression An expression that returns a CustomXMLValidationError object.

Return Value

String

See also

Concepts

CustomXMLValidationError Object

Other resources

CustomXMLValidationError Object Members


CustomXMLValidationError.Type Property (Office)

 Copy code hover
[image]

CustomXMLValidationError.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the type of error generated from the CustomXMLValidationError object. Read-only.

Syntax

expression .Type

expression An expression that returns a CustomXMLValidationError object.

Return Value

MsoCustomXMLValidationErrorType

See also

Concepts

CustomXMLValidationError Object

Other resources

CustomXMLValidationError Object Members


CustomXMLValidationError Methods (Office)

 Copy code hover
[image]

CustomXMLValidationError Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes the CustomXMLValidationError object representing a data validation error.


CustomXMLValidationError.Delete Method (Office)

 Copy code hover
[image]

CustomXMLValidationError.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the CustomXMLValidationError object representing a data validation error.

Syntax

expression .Delete

expression An expression that returns a CustomXMLValidationError object.

Example

The following example deletes the validation error containing specific text.

VBA Copy code Copy code
Dim objCustomXMLValidationError as CustomXMLValidationError

' Deletes the specified error message.
objCustomXMLValidationError.Text("To add content to this data stream, it must be valid, well-formed XML." ).Delete

See also

Concepts

CustomXMLValidationError Object

Other resources

CustomXMLValidationError Object Members


CustomXMLValidationErrors Object (Office)

 Copy code hover
[image]

CustomXMLValidationErrors Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of CustomXMLValidationError objects.

Example

The following example adds a custom part and then adds a child node to that part. Any errors that occur are added to the CustomXMLValidationErrors collection and then displayed in the Debug window.

VBA Copy code Copy code
Dim ValErrors As CustomXMLValidationErrors
Dim ValError As CustomXMLValidationError
Dim cxp1 As CustomXMLPart
Dim intError As Integer

On Error Go To validation_error

 With ActiveDocument

    ' Add and populate a custom xml part
    set cxp1 = .CustomXMLParts.Add "<invoice>"

    ' Add a node
    cxp1.AddNode "<quantity>", "supplier", "urn:invoice:namespace"

 End With

If ValErrors.Count > 0 then
   For Each ValError In ValErrors
      DeBug.Print("Error name: " & ValError.Name & " Error description: " & ValError.Text)
   Next
End If

Exit Sub

validation_error:
   CustomXMLValidationErrors.Add(ValError.Name, ValError.Text))
Resume

See also

Concepts

Object Model Reference

Other resources

CustomXMLValidationErrors Object Members


CustomXMLValidationErrors Members (Office)

 Copy code hover
[image]

CustomXMLValidationErrors Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of CustomXMLValidationError objects.

Methods

Name | Description
Add | Adds a CustomXMLValidationError object containing an XML validation error to the CustomXMLValidationErrors collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLValidationErrors object. Read-only.
Count | Gets a Long indicating the number of items in the CustomXMLValidationErrors collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLValidationErrors object was created. Read-only.
Item | Gets a CustomXMLValidationError object from the CustomXMLValidationErrors collection. Read-only.
Parent | Gets the Parent object for the CustomXMLValidationErrors object. Read-only.


CustomXMLValidationErrors Properties (Office)

 Copy code hover
[image]

CustomXMLValidationErrors Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the CustomXMLValidationErrors object. Read-only.
Count | Gets a Long indicating the number of items in the CustomXMLValidationErrors collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the CustomXMLValidationErrors object was created. Read-only.
Item | Gets a CustomXMLValidationError object from the CustomXMLValidationErrors collection. Read-only.
Parent | Gets the Parent object for the CustomXMLValidationErrors object. Read-only.


CustomXMLValidationErrors.Application Property (Office)

 Copy code hover
[image]

CustomXMLValidationErrors.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the CustomXMLValidationErrors object. Read-only.

Syntax

expression .Application

expression An expression that returns a CustomXMLValidationErrors object.

Return Value

Object

See also

Concepts

CustomXMLValidationErrors Object

Other resources

CustomXMLValidationErrors Object Members


CustomXMLValidationErrors.Count Property (Office)

 Copy code hover
[image]

CustomXMLValidationErrors.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the CustomXMLValidationErrors collection. Read-only.

Syntax

expression .Count

expression An expression that returns a CustomXMLValidationErrors object.

Return Value

Long

See also

Concepts

CustomXMLValidationErrors Object

Other resources

CustomXMLValidationErrors Object Members


CustomXMLValidationErrors.Creator Property (Office)

 Copy code hover
[image]

CustomXMLValidationErrors.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the CustomXMLValidationErrors object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a CustomXMLValidationErrors object.

Return Value

Long

See also

Concepts

CustomXMLValidationErrors Object

Other resources

CustomXMLValidationErrors Object Members


CustomXMLValidationErrors.Item Property (Office)

 Copy code hover
[image]

CustomXMLValidationErrors.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CustomXMLValidationError object from the CustomXMLValidationErrors collection. Read-only.

Syntax

expression .Item(Index)

expression An expression that returns a CustomXMLValidationErrors object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | The name or index number of the CustomXMLValidationError object to be returned.

Return Value

CustomXMLValidationError

See also

Concepts

CustomXMLValidationErrors Object

Other resources

CustomXMLValidationErrors Object Members


CustomXMLValidationErrors.Parent Property (Office)

 Copy code hover
[image]

CustomXMLValidationErrors.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the CustomXMLValidationErrors object. Read-only.

Syntax

expression .Parent

expression An expression that returns a CustomXMLValidationErrors object.

Return Value

Object

See also

Concepts

CustomXMLValidationErrors Object

Other resources

CustomXMLValidationErrors Object Members


CustomXMLValidationErrors Methods (Office)

 Copy code hover
[image]

CustomXMLValidationErrors Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a CustomXMLValidationError object containing an XML validation error to the CustomXMLValidationErrors collection.


CustomXMLValidationErrors.Add Method (Office)

 Copy code hover
[image]

CustomXMLValidationErrors.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a CustomXMLValidationError object containing an XML validation error to the CustomXMLValidationErrors collection.

Syntax

expression .Add(Node, ErrorName, ErrorText, ClearedOnUpdate)

expression An expression that returns a CustomXMLValidationErrors object.

Parameters

Name | Required/Optional | Data Type | Description
Node | Required | CustomXMLNode | Represents the node where the error occurred.
ErrorName | Required | String | Contains the name of the error.
ErrorText | Optional | String | Contains the descriptive error text.
ClearedOnUpdate | Optional | Boolean | Specifies whether the error is to be cleared from the CustomXMLValidationErrors collection when the XML is corrected and updated.

Example

The following example adds an error message to the collection.

VBA Copy code Copy code
Dim objCustomXMLValidationErrors as CustomXMLValidationErrors

On Error GoTo Err

' Adds the specified error message to the collection.
objCustomXMLValidationErrors.Add("//badTag", "ValidationError", "To add content to this stream, it must be valid, well-formed XML.", True)

See also

Concepts

CustomXMLValidationErrors Object

Other resources

CustomXMLValidationErrors Object Members


DocumentInspector Object (Office)

 Copy code hover
[image]

DocumentInspector Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a Document Inspector module in a DocumentInspectors collection.

Remarks

DocumentInspector object provides access to the Inspect and Fix methods. The DocumentInspector object represents custom Document Inspector modules and some "built-in" options. To see the list of built-in options, open the Document Inspector dialog box from the File menu. The first two options (Comments, Revisions, Versions, and Annotations; Document Properties and Personal Information) are not listed in the DocumentInspectors collection; instead their functionality is available through the RemoveDocumentInformation method. The remaining options in the dialog box and any installed custom modules developed by third-party sources are available from the DocumentInspectors collection by specifying an index value.

Example

The following example inspects a document using a Document Inspector module and displays the status and results of the inspection.

VBA Copy code Copy code
Public Sub DI_InspectDocument()
Dim docStatus As MsoDocInspectorStatus
Dim result As String
ActiveDocument.DocumentInspectors(3).Inspect docStatus, results

MsgBox ("The inspection returned the following status " & docStatus & _
" with this result " & result)
End Sub

See also

Concepts

Object Model Reference

Other resources

DocumentInspector Object Members


DocumentInspector Members (Office)

 Copy code hover
[image]

DocumentInspector Members (Office)
Send feedback

Published: July 09, 2012

Represents a Document Inspector module in a DocumentInspectors collection.

Methods

Name | Description
Fix | Performs an action on specific information items or document properties depending on the Document Inspector module specified.
Inspect | Inspects a document for specific information or document properties.

Properties

Name | Description
Application | Gets an Application object that represents the creator of the DocumentInspector object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentInspector object was created. Read-only.
Description | Gets the description of the DocumentInspector object. Read-only.
Name | Gets the name of the module represented by a DocumentInspector object. Read-only.
Parent | Gets an object that represents the parent of the DocumentInspector object. Read-only.


DocumentInspector Properties (Office)

 Copy code hover
[image]

DocumentInspector Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the creator of the DocumentInspector object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentInspector object was created. Read-only.
Description | Gets the description of the DocumentInspector object. Read-only.
Name | Gets the name of the module represented by a DocumentInspector object. Read-only.
Parent | Gets an object that represents the parent of the DocumentInspector object. Read-only.


DocumentInspector.Application Property (Office)

 Copy code hover
[image]

DocumentInspector.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the creator of the DocumentInspector object. Read-only.

Syntax

expression .Application

expression An expression that returns a DocumentInspector object.

Return Value

Object

See also

Concepts

DocumentInspector Object

Other resources

DocumentInspector Object Members


DocumentInspector.Creator Property (Office)

 Copy code hover
[image]

DocumentInspector.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the DocumentInspector object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a DocumentInspector object.

Return Value

Long

See also

Concepts

DocumentInspector Object

Other resources

DocumentInspector Object Members


DocumentInspector.Description Property (Office)

 Copy code hover
[image]

DocumentInspector.Description Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the description of the DocumentInspector object. Read-only.

Syntax

expression .Description

expression An expression that returns a DocumentInspector object.

Return Value

String

See also

Concepts

DocumentInspector Object

Other resources

DocumentInspector Object Members


DocumentInspector.Name Property (Office)

 Copy code hover
[image]

DocumentInspector.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the module represented by a DocumentInspector object. Read-only.

Syntax

expression .Name

expression An expression that returns a DocumentInspector object.

Return Value

String

See also

Concepts

DocumentInspector Object

Other resources

DocumentInspector Object Members


DocumentInspector.Parent Property (Office)

 Copy code hover
[image]

DocumentInspector.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an object that represents the parent of the DocumentInspector object. Read-only.

Syntax

expression .Parent

expression An expression that returns a DocumentInspector object.

Return Value

Object

See also

Concepts

DocumentInspector Object

Other resources

DocumentInspector Object Members


DocumentInspector Methods (Office)

 Copy code hover
[image]

DocumentInspector Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Fix | Performs an action on specific information items or document properties depending on the Document Inspector module specified.
Inspect | Inspects a document for specific information or document properties.


DocumentInspector.Fix Method (Office)

 Copy code hover
[image]

DocumentInspector.Fix Method (Office)
See also Send feedback

Published: July 09, 2012

Performs an action on specific information items or document properties depending on the Document Inspector module specified.

Syntax

expression .Fix(Status, Results)

expression An expression that returns a DocumentInspector object.

Parameters

Name | Required/Optional | Data Type | Description
Status | Required | MsoDocInspectorStatus | An enumeration representing that staus of the document. Status is an output parameter, which means that its value is returned when the method has completed its purpose.
Results | Required | String | Contains the results of the action. Results is an output parameter.

Remarks

MsoDocInspectorStatus members

There are two Document Inspector modules that are included with Microsoft Office. These are the Comments/Revisions module and the Document Properties method. These are the first two options that show up in the Document Inspector dialog box but are not available in the DocumentInspectors collection.

Example

The following example demonstrates implementing the Fix method of the DocumentInspector object. You specify which Document Inspector module to execute with the index value specified in the DocumentInspectors collection. Before executing this method, you would likely run the Inspect method to determine if there are any hidden worksheets in the workbook.

VBA Copy code Copy code
Public Sub DI_FixDocument()
Dim docStatus As MsoDocInspectorStatus
Dim result As String
ActiveDocument.DocumentInspectors(3).Fix docStatus, result

MsgBox ("The Fix method returned the following status " & docStatus & _
" with this result " & result)
End Sub

See also

Concepts

DocumentInspector Object

Other resources

DocumentInspector Object Members


DocumentInspector.Inspect Method (Office)

 Copy code hover
[image]

DocumentInspector.Inspect Method (Office)
See also Send feedback

Published: July 09, 2012

Inspects a document for specific information or document properties.

Syntax

expression .Inspect(Status, Results)

expression An expression that returns a DocumentInspector object.

Parameters

Name | Required/Optional | Data Type | Description
Status | Required | MsoDocInspectorStatus | An enumeration representing that status of the document. Status is an output parameter which means that its value is returned when the method has completed its purpose.
Results | Required | String | Contains a lists the information items or document properties found in the document.

Remarks

MsoDocInspectorStatus members

Example

The following example inspects a document using Inspect method of the DocumentInspector object and then displays the status and results of the inspection.

VBA Copy code Copy code
Public Sub DI_InspectDocument()
Dim docStatus As MsoDocInspectorStatus
Dim result As String
ActiveDocument.DocumentInspectors(1).Inspect docStatus, results

MsgBox ("The inspection returned the following status " & docStatus & _
" with this result " & result)
End Sub

See also

Concepts

DocumentInspector Object

Other resources

DocumentInspector Object Members


DocumentInspectors Object (Office)

 Copy code hover
[image]

DocumentInspectors Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of DocumentInspector objects.

Remarks

The DocumentInspectors collection is part of the Document object in Microsoft Word, the Workbook object in Microsoft Excel, and the Presentation object in MicrosoftPowerPoint. A DocumentInspectors collection contains multiple DocumentInspector objects, one for some built-in options and each installed custom Document Inspector module. For more information, see the DocumentInspector help topic.

Example

The following example calls the Fix method of a Document Inspector module and displays the status of the action and the specific items that are removed.

VBA Copy code Copy code
Public Sub FixDocument()
Dim docStatus As MsoDocInspectorStatus
Dim results As String
 ActiveDocument.DocumentInspectors(3).Fix docStatus, results

 MsgBox docStatus
 MsgBox("The following items were removed " & results)

End Sub

See also

Concepts

Object Model Reference

Other resources

DocumentInspectors Object Members


DocumentInspectors Members (Office)

 Copy code hover
[image]

DocumentInspectors Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of DocumentInspector objects.

Properties

Name | Description
Application | Gets an Application object that represents the creator of the DocumentInspectors object. Read-only.
Count | Gets the number of items in the DocumentInspectors object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentInspectors object was created. Read-only.
Item | Gets the DocumentInspector object specified by the index. Read-only.
Parent | Gets an object that represents the parent of a DocumentInspectors object. Read-only.


DocumentInspectors Properties (Office)

 Copy code hover
[image]

DocumentInspectors Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the creator of the DocumentInspectors object. Read-only.
Count | Gets the number of items in the DocumentInspectors object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentInspectors object was created. Read-only.
Item | Gets the DocumentInspector object specified by the index. Read-only.
Parent | Gets an object that represents the parent of a DocumentInspectors object. Read-only.


DocumentInspectors.Application Property (Office)

 Copy code hover
[image]

DocumentInspectors.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the creator of the DocumentInspectors object. Read-only.

Syntax

expression .Application

expression An expression that returns a DocumentInspectors object.

Return Value

Object

See also

Concepts

DocumentInspectors Object

Other resources

DocumentInspectors Object Members


DocumentInspectors.Count Property (Office)

 Copy code hover
[image]

DocumentInspectors.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the number of items in the DocumentInspectors object. Read-only.

Syntax

expression .Count

expression An expression that returns a DocumentInspectors object.

Return Value

Integer

See also

Concepts

DocumentInspectors Object

Other resources

DocumentInspectors Object Members


DocumentInspectors.Creator Property (Office)

 Copy code hover
[image]

DocumentInspectors.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the DocumentInspectors object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a DocumentInspectors object.

Return Value

Long

See also

Concepts

DocumentInspectors Object

Other resources

DocumentInspectors Object Members


DocumentInspectors.Item Property (Office)

 Copy code hover
[image]

DocumentInspectors.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the DocumentInspector object specified by the index. Read-only.

Syntax

expression .Item(Index)

expression An expression that returns a DocumentInspectors object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Integer | The index number of the object.

Return Value

DocumentInspector

See also

Concepts

DocumentInspectors Object

Other resources

DocumentInspectors Object Members


DocumentInspectors.Parent Property (Office)

 Copy code hover
[image]

DocumentInspectors.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an object that represents the parent of a DocumentInspectors object. Read-only.

Syntax

expression .Parent

expression An expression that returns a DocumentInspectors object.

Return Value

Object

See also

Concepts

DocumentInspectors Object

Other resources

DocumentInspectors Object Members


DocumentLibraryVersion Object (Office)

 Copy code hover
[image]

DocumentLibraryVersion Object (Office)
See also Send feedback

Published: July 09, 2012

The DocumentLibraryVersion object represents a single saved version of a shared document which has versioning enabled and which is stored in a document library on the server. Each DocumentLibraryVersion object is a member of the active document's DocumentLibraryVersions collection.

Remarks

Each DocumentLibraryVersion object represents one saved version of the active document. When versioning is enabled, a new version is created on the server when the actions listed below occur; additional versions are not created each time the user saves changes to the open document.

  • Check In

  • Save - A new version is created on the server when the user first saves the document after opening it. Additional changes saved while the document is open apply to the same version.

  • Restore

  • Upload

Use the Modified, ModifiedBy, and Comments properties to return information about a saved version of a shared document.

Use the Open method to open a previous version, or the Restore method to restore a previous version in place of the current version. Use the Delete method to delete a version.

Example

The following example displays the properties of each saved version of the active document.

VBA Copy code Copy code
 Dim dlvVersions As Office.DocumentLibraryVersions
 Dim dlvVersion As Office.DocumentLibraryVersion
 Dim strVersionInfo As String
 Set dlvVersions = ActiveDocument.DocumentLibraryVersions
 If dlvVersions.IsVersioningEnabled Then
 strVersionInfo = "This document has " & _
 dlvVersions.Count & " versions: " & vbCrLf
 For Each dlvVersion In dlvVersions
 strVersionInfo = strVersionInfo & _
 " - Version #: " & dlvVersion.Index & vbCrLf & _
 " - Modified by: " & dlvVersion.ModifiedBy & vbCrLf & _
 " - Modified on: " & dlvVersion.Modified & vbCrLf & _
 " - Comments: " & dlvVersion.Comments & vbCrLf
 Next
 Else
 strVersionInfo = "Versioning not enabled for this document."
 End If
 MsgBox strVersionInfo, vbInformation + vbOKOnly, "Version Information"
 Set dlvVersion = Nothing
 Set dlvVersions = Nothing

See also

Concepts

Object Model Reference

Other resources

DocumentLibraryVersion Object Members


DocumentLibraryVersion Members (Office)

 Copy code hover
[image]

DocumentLibraryVersion Members (Office)
Send feedback

Published: July 09, 2012

The DocumentLibraryVersion object represents a single saved version of a shared document which has versioning enabled and which is stored in a document library on the server. Each DocumentLibraryVersion object is a member of the active document's DocumentLibraryVersions collection.

Methods

Name | Description
Delete | Removes a document library version from the DocumentLibraryVersions collection.
Open | Opens the specified version of the shared document from the DocumentLibraryVersions collection in read-only mode.
Restore | Restores a previous saved version of a shared document from the DocumentLibraryVersions collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the DocumentLibraryVersion object (you can use this property with an Automation object to return that object's container application). Read-only.
Comments | Gets any optional comments associated with the specified version of the shared document. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentLibraryVersion object was created. Read-only.
Index | Gets a Long representing the index number for a DocumentLibraryVersion object in the collection. Read-only.
Modified | Gets the date and time at which the specified version of the shared document was last saved to the server. Read-only.
ModifiedBy | Gets the name of the user who last saved the specified version of the shared document to the server. Read-only.
Parent | Gets the Parent object for the DocumentLibraryVersion object. Read-only.


DocumentLibraryVersion Properties (Office)

 Copy code hover
[image]

DocumentLibraryVersion Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the DocumentLibraryVersion object (you can use this property with an Automation object to return that object's container application). Read-only.
Comments | Gets any optional comments associated with the specified version of the shared document. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentLibraryVersion object was created. Read-only.
Index | Gets a Long representing the index number for a DocumentLibraryVersion object in the collection. Read-only.
Modified | Gets the date and time at which the specified version of the shared document was last saved to the server. Read-only.
ModifiedBy | Gets the name of the user who last saved the specified version of the shared document to the server. Read-only.
Parent | Gets the Parent object for the DocumentLibraryVersion object. Read-only.


DocumentLibraryVersion.Application Property (Office)

 Copy code hover
[image]

DocumentLibraryVersion.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the DocumentLibraryVersion object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a DocumentLibraryVersion object.

Return Value

Object

See also

Concepts

DocumentLibraryVersion Object

Other resources

DocumentLibraryVersion Object Members


DocumentLibraryVersion.Comments Property (Office)

 Copy code hover
[image]

DocumentLibraryVersion.Comments Property (Office)
See also Send feedback

Published: July 09, 2012

Gets any optional comments associated with the specified version of the shared document. Read-only.

Syntax

expression .Comments

expression A variable that represents a DocumentLibraryVersion object.

Remarks

A user can attach version comments through the document library user interface when checking in a document that was previously checked out.

Example

The following example lists comments and other properties for each version of a shared document.

Copy code Copy code
 Dim dlvVersions As Office.DocumentLibraryVersions
 Dim dlvVersion As Office.DocumentLibraryVersion
 Dim strVersionInfo As String
 Set dlvVersions = ActiveDocument.DocumentLibraryVersions
 If dlvVersions.IsVersioningEnabled Then
 strVersionInfo = "This document has " & _
 dlvVersions.Count & " versions: " & vbCrLf
 For Each dlvVersion In dlvVersions
 strVersionInfo = strVersionInfo & _
 " - Version #: " & dlvVersion.Index & vbCrLf & _
 " - Modified by: " & dlvVersion.ModifiedBy & vbCrLf & _
 " - Modified on: " & dlvVersion.Modified & vbCrLf & _
 " - Comments: " & dlvVersion.Comments & vbCrLf
 Next
 Else
 strVersionInfo = "Versioning not enabled for this document."
 End If
 MsgBox strVersionInfo, vbInformation + vbOKOnly, "Version Information"
 Set dlvVersion = Nothing
 Set dlvVersions = Nothing

See also

Concepts

DocumentLibraryVersion Object

Other resources

DocumentLibraryVersion Object Members


DocumentLibraryVersion.Creator Property (Office)

 Copy code hover
[image]

DocumentLibraryVersion.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the DocumentLibraryVersion object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a DocumentLibraryVersion object.

Return Value

Long

See also

Concepts

DocumentLibraryVersion Object

Other resources

DocumentLibraryVersion Object Members


DocumentLibraryVersion.Index Property (Office)

 Copy code hover
[image]

DocumentLibraryVersion.Index Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long representing the index number for a DocumentLibraryVersion object in the collection. Read-only.

Syntax

expression .Index

expression A variable that represents a DocumentLibraryVersion object.

Return Value

Long

See also

Concepts

DocumentLibraryVersion Object

Other resources

DocumentLibraryVersion Object Members


DocumentLibraryVersion.Modified Property (Office)

 Copy code hover
[image]

DocumentLibraryVersion.Modified Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the date and time at which the specified version of the shared document was last saved to the server. Read-only.

Syntax

expression .Modified

expression A variable that represents a DocumentLibraryVersion object.

Remarks

A new version is created on the server each time a user opens the document and is updated when the user saves changes; additional versions are not created each time the user saves changes to the open document. The Modified property of the active document version represents the last time the user saved changes to the open document.

Example

The following example displays the Modified date and time along with other properties of each version of a shared document.

Copy code Copy code
 Dim dlvVersions As Office.DocumentLibraryVersions
 Dim dlvVersion As Office.DocumentLibraryVersion
 Dim strVersionInfo As String
 Set dlvVersions = ActiveDocument.DocumentLibraryVersions
 If dlvVersions.IsVersioningEnabled Then
 strVersionInfo = "This document has " & _
 dlvVersions.Count & " versions: " & vbCrLf
 For Each dlvVersion In dlvVersions
 strVersionInfo = strVersionInfo & _
 " - Version #: " & dlvVersion.Index & vbCrLf & _
 " - Modified by: " & dlvVersion.ModifiedBy & vbCrLf & _
 " - Modified on: " & dlvVersion.Modified & vbCrLf & _
 " - Comments: " & dlvVersion.Comments & vbCrLf
 Next
 Else
 strVersionInfo = "Versioning not enabled for this document."
 End If
 MsgBox strVersionInfo, vbInformation + vbOKOnly, "Version Information"
 Set dlvVersion = Nothing
 Set dlvVersions = Nothing

See also

Concepts

DocumentLibraryVersion Object

Other resources

DocumentLibraryVersion Object Members


DocumentLibraryVersion.ModifiedBy Property (Office)

 Copy code hover
[image]

DocumentLibraryVersion.ModifiedBy Property (Office)
See also Send feedback

Published: July 16, 2012

Gets the name of the user who last saved the specified version of the shared document to the server. Read-only.

Syntax

expression .ModifiedBy

expression A variable that represents a DocumentLibraryVersion object.

Return Value

String

See also

Concepts

DocumentLibraryVersion Object

Other resources

DocumentLibraryVersion Object Members


DocumentLibraryVersion.Parent Property (Office)

 Copy code hover
[image]

DocumentLibraryVersion.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the DocumentLibraryVersion object. Read-only.

Syntax

expression .Parent

expression A variable that represents a DocumentLibraryVersion object.

Return Value

Object

See also

Concepts

DocumentLibraryVersion Object

Other resources

DocumentLibraryVersion Object Members


DocumentLibraryVersion Methods (Office)

 Copy code hover
[image]

DocumentLibraryVersion Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Removes a document library version from the DocumentLibraryVersions collection.
Open | Opens the specified version of the shared document from the DocumentLibraryVersions collection in read-only mode.
Restore | Restores a previous saved version of a shared document from the DocumentLibraryVersions collection.


DocumentLibraryVersion.Delete Method (Office)

 Copy code hover
[image]

DocumentLibraryVersion.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Removes a document library version from the DocumentLibraryVersions collection.

Syntax

expression .Delete

expression Required. A variable that represents a DocumentLibraryVersion object.

See also

Concepts

DocumentLibraryVersion Object

Other resources

DocumentLibraryVersion Object Members


DocumentLibraryVersion.Open Method (Office)

 Copy code hover
[image]

DocumentLibraryVersion.Open Method (Office)
See also Send feedback

Published: July 09, 2012

Opens the specified version of the shared document from the DocumentLibraryVersions collection in read-only mode.

Syntax

expression .Open

expression Required. A variable that represents a DocumentLibraryVersion object.

Example

The following example opens the previous saved version of the active document in read-only mode.

VBA Copy code Copy code
 Dim dlvVersions As Office.DocumentLibraryVersions
 Set dlvVersions = ActiveDocument.DocumentLibraryVersions
 dlvVersions(dlvVersions.Count - 1).Open
 Set dlvVersions = Nothing

See also

Concepts

DocumentLibraryVersion Object

Other resources

DocumentLibraryVersion Object Members


DocumentLibraryVersion.Restore Method (Office)

 Copy code hover
[image]

DocumentLibraryVersion.Restore Method (Office)
See also Send feedback

Published: July 09, 2012

Restores a previous saved version of a shared document from the DocumentLibraryVersions collection.

Syntax

expression .Restore

expression A variable that represents a DocumentLibraryVersion object.

Return Value

Object

Remarks

Use the Restore method to return to an earlier saved version of the active document. The Restore method does several things:

  1. It changes the open version of the shared document to read-only mode but leaves it open.

  2. It opens the restored version in read/write mode.

  3. It saves the restored version to the server as a new document version, making the restored version the latest version.

The Restore method raises a run-time error if the active document has changes that have not been saved.

Example

The following example restores the previous version of the active document.

Copy code Copy code
 Dim dlvVersions As Office.DocumentLibraryVersions
 Set dlvVersions = ActiveDocument.DocumentLibraryVersions
 dlvVersions(dlvVersions.Count - 1).Restore
 Set dlvVersions = Nothing

See also

Concepts

DocumentLibraryVersion Object

Other resources

DocumentLibraryVersion Object Members


DocumentLibraryVersions Object (Office)

 Copy code hover
[image]

DocumentLibraryVersions Object (Office)
See also Send feedback

Published: July 09, 2012

The DocumentLibraryVersions property of the Document object in Microsoft Word, the Workbook object in Microsoft Excel, and the Presentation object in Microsoft PowerPoint returns a DocumentLibraryVersions object. The DocumentLibraryVersions object represents a collection of DocumentLibraryVersion objects.

Remarks

Use the DocumentLibraryVersions object with documents stored in a SharePoint document library on the server to determine whether versioning is enabled for the active document and, if versioning is enabled, to manage the document's collection of DocumentLibraryVersion objects.

Each DocumentLibraryVersion object represents one saved version of the active document. When versioning is enabled, a new version is created on the server when the actions listed below occur; additional versions are not created each time the user saves changes to the open document.

  • Check In

  • Save - A new version is created on the server when the user first saves the document after opening it. Additional changes saved while the document is open apply to the same version.

  • Restore

  • Upload

The DocumentLibraryVersions object model is available whether versioning is enabled or disabled on the active document. The DocumentLibraryVersions property of the Document, Workbook and Presentation objects does not return Nothing when the active document is not stored in a document library or versioning is not enabled. Use the IsVersioningEnabled property to determine whether the document library is configured to save a backup copy, or version, each time the document is edited on the Web site.

Example

The following example checks to see whether versioning is enabled for the active document and, if so, displays information about each saved version.

VBA Copy code Copy code
Dim dlvVersions As Office.DocumentLibraryVersions
 Dim dlvVersion As Office.DocumentLibraryVersion
 Dim strVersionInfo As String
 Set dlvVersions = ActiveDocument.DocumentLibraryVersions
 If dlvVersions.IsVersioningEnabled Then
 strVersionInfo = "This document has " & _
 dlvVersions.Count & " versions: " & vbCrLf
 For Each dlvVersion In dlvVersions
 strVersionInfo = strVersionInfo & _
 " - Version #: " & dlvVersion.Index & vbCrLf & _
 " - Modified by: " & dlvVersion.ModifiedBy & vbCrLf & _
 " - Modified on: " & dlvVersion.Modified & vbCrLf & _
 " - Comments: " & dlvVersion.Comments & vbCrLf
 Next
 Else
 strVersionInfo = "Versioning not enabled for this document."
 End If
 MsgBox strVersionInfo, vbInformation + vbOKOnly, "Version Information"
 Set dlvVersion = Nothing
 Set dlvVersions = Nothing

See also

Concepts

Object Model Reference

Other resources

DocumentLibraryVersions Object Members


DocumentLibraryVersions Members (Office)

 Copy code hover
[image]

DocumentLibraryVersions Members (Office)
Send feedback

Published: July 09, 2012

The DocumentLibraryVersions property of the Document object in Microsoft Word, the Workbook object in Microsoft Excel, and the Presentation object in Microsoft PowerPoint returns a DocumentLibraryVersions object. The DocumentLibraryVersions object represents a collection of DocumentLibraryVersion objects.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the DocumentLibraryVersions object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the DocumentLibraryVersions collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentLibraryVersions object was created. Read-only.
IsVersioningEnabled | Gets a Boolean value that indicates whether the document library in which the active document is saved on the server is configured to create a backup copy, or version, each time the file is edited on the Web site. Read-only.
Item | Gets a DocumentLibraryVersion object from the DocumentLibraryVersions collection. Read-only.
Parent | Gets the Parent object for the DocumentLibraryVersions object. Read-only.


DocumentLibraryVersions Properties (Office)

 Copy code hover
[image]

DocumentLibraryVersions Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the DocumentLibraryVersions object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the DocumentLibraryVersions collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentLibraryVersions object was created. Read-only.
IsVersioningEnabled | Gets a Boolean value that indicates whether the document library in which the active document is saved on the server is configured to create a backup copy, or version, each time the file is edited on the Web site. Read-only.
Item | Gets a DocumentLibraryVersion object from the DocumentLibraryVersions collection. Read-only.
Parent | Gets the Parent object for the DocumentLibraryVersions object. Read-only.


DocumentLibraryVersions.Application Property (Office)

 Copy code hover
[image]

DocumentLibraryVersions.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the DocumentLibraryVersions object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a DocumentLibraryVersions object.

Return Value

Object

See also

Concepts

DocumentLibraryVersions Object

Other resources

DocumentLibraryVersions Object Members


DocumentLibraryVersions.Count Property (Office)

 Copy code hover
[image]

DocumentLibraryVersions.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the DocumentLibraryVersions collection. Read-only.

Syntax

expression .Count

expression A variable that represents a DocumentLibraryVersions object.

Return Value

Long

See also

Concepts

DocumentLibraryVersions Object

Other resources

DocumentLibraryVersions Object Members


DocumentLibraryVersions.Creator Property (Office)

 Copy code hover
[image]

DocumentLibraryVersions.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the DocumentLibraryVersions object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a DocumentLibraryVersions object.

Return Value

Long

See also

Concepts

DocumentLibraryVersions Object

Other resources

DocumentLibraryVersions Object Members


DocumentLibraryVersions.IsVersioningEnabled Property (Office)

 Copy code hover
[image]

DocumentLibraryVersions.IsVersioningEnabled Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value that indicates whether the document library in which the active document is saved on the server is configured to create a backup copy, or version, each time the file is edited on the Web site. Read-only.

Syntax

expression .IsVersioningEnabled

expression A variable that represents a DocumentLibraryVersions object.

Remarks

Versioning is enabled or disabled on the document library and not on individual documents. Therefore the value of the IsVersioningEnabled property depends on the document library in which the document is saved.

Example

The following example displays the number of saved versions of the active document, if versioning is enabled.

Copy code Copy code
 Dim dlvVersions As Office.DocumentLibraryVersions
 Set dlvVersions = ActiveDocument.DocumentLibraryVersions
 If dlvVersions.IsVersioningEnabled Then
 MsgBox "This document has " & dlvVersions.Count & _
 " saved versions.", vbInformation + vbOKOnly, _
 "Version Information"
 Else
 MsgBox "Versioning is not enabled for this document.", _
 vbInformation + vbOKOnly, "No Versioning"
 End If
 Set dlvVersions = Nothing

See also

Concepts

DocumentLibraryVersions Object

Other resources

DocumentLibraryVersions Object Members


DocumentLibraryVersions.Item Property (Office)

 Copy code hover
[image]

DocumentLibraryVersions.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a DocumentLibraryVersion object from the DocumentLibraryVersions collection. Read-only.

Syntax

expression .Item(Index)

expression Required. A variable that represents a DocumentLibraryVersions object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | The index number of the DocumentLibraryVersion returned.

See also

Concepts

DocumentLibraryVersions Object

Other resources

DocumentLibraryVersions Object Members


DocumentLibraryVersions.Parent Property (Office)

 Copy code hover
[image]

DocumentLibraryVersions.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the DocumentLibraryVersions object. Read-only.

Syntax

expression .Parent

expression A variable that represents a DocumentLibraryVersions object.

Return Value

Object

See also

Concepts

DocumentLibraryVersions Object

Other resources

DocumentLibraryVersions Object Members


DocumentProperties Object (Office)

 Copy code hover
[image]

DocumentProperties Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of DocumentProperty objects. Each DocumentProperty object represents a built-in or custom property of a container document.

Remarks

Use the Add method to create a new custom property and add it to the DocumentProperties collection. You cannot use the Add method to create a built-in document property.

Use BuiltinDocumentProperties(index), where index is the index number of the built-in document property, to return a single DocumentProperty object that represents a specific built-in document property. Use CustomDocumentProperties(index), where index is the number of the custom document property, to return a DocumentProperty object that represents a specific custom document property.

See also

Concepts

Object Model Reference

Other resources

DocumentProperties Object Members


DocumentProperties Members (Office)

 Copy code hover
[image]

DocumentProperties Members (Office)
Send feedback

Published: July 09, 2012

A collection of DocumentProperty objects. Each DocumentProperty object represents a built-in or custom property of a container document.

Methods

Name | Description
Add | Creates a new custom document property. You can add a new document property only to the custom DocumentProperties collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the DocumentProperties object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the DocumentProperties collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentProperties object was created. Read-only.
Item | Gets a DocumentProperty object from the DocumentProperties collection. Read-only.
Parent | Gets the Parent object for the DocumentProperties object. Read-only.


DocumentProperties Properties (Office)

 Copy code hover
[image]

DocumentProperties Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the DocumentProperties object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the DocumentProperties collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentProperties object was created. Read-only.
Item | Gets a DocumentProperty object from the DocumentProperties collection. Read-only.
Parent | Gets the Parent object for the DocumentProperties object. Read-only.


DocumentProperties.Application Property (Office)

 Copy code hover
[image]

DocumentProperties.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the DocumentProperties object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application(ppidisp)

expression A variable that represents a DocumentProperties object.

Parameters

Name | Required/Optional | Data Type | Description
ppidisp | Required | Object | Represents the identifier for a document property.

Return Value

[HRESULT]

See also

Concepts

DocumentProperties Object

Other resources

DocumentProperties Object Members


DocumentProperties.Count Property (Office)

 Copy code hover
[image]

DocumentProperties.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the DocumentProperties collection. Read-only.

Syntax

expression .Count(pc)

expression A variable that represents a DocumentProperties object.

Parameters

Name | Required/Optional | Data Type | Description
pc | Required | Long | Represents the index of the document property.

Return Value

Long

Example

This example displays the number of custom document properties in the active document.

VBA Copy code Copy code
MsgBox ("There are " & _
 ActiveDocument.CustomDocumentProperties.Count & _
 " custom document properties in the " & _
 "active document.")

See also

Concepts

DocumentProperties Object

Other resources

DocumentProperties Object Members


DocumentProperties.Creator Property (Office)

 Copy code hover
[image]

DocumentProperties.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the DocumentProperties object was created. Read-only.

Syntax

expression .Creator(plCreator)

expression A variable that represents a DocumentProperties object.

Parameters

Name | Required/Optional | Data Type | Description
plCreator | Required | Long | The name or index number of the built-in document property.

Return Value

[HRESULT]

See also

Concepts

DocumentProperties Object

Other resources

DocumentProperties Object Members


DocumentProperties.Item Property (Office)

 Copy code hover
[image]

DocumentProperties.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a DocumentProperty object from the DocumentProperties collection. Read-only.

Syntax

expression .Item(Index)

expression Required. A variable that represents a DocumentProperties object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | The name or index number of the document property returned.

See also

Concepts

DocumentProperties Object

Other resources

DocumentProperties Object Members


DocumentProperties.Parent Property (Office)

 Copy code hover
[image]

DocumentProperties.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the DocumentProperties object. Read-only.

Syntax

expression .Parent

expression A variable that represents a DocumentProperties object.

Return Value

Object

Example

This example displays the name of the parent object for a document property. You must pass a valid DocumentProperty object to the procedure.

VBA Copy code Copy code
Sub DisplayParent(dp as DocumentProperty)
 MsgBox dp.Parent.Name
End Sub

See also

Concepts

DocumentProperties Object

Other resources

DocumentProperties Object Members


DocumentProperties Methods (Office)

 Copy code hover
[image]

DocumentProperties Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Creates a new custom document property. You can add a new document property only to the custom DocumentProperties collection.


DocumentProperties.Add Method (Office)

 Copy code hover
[image]

DocumentProperties.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Creates a new custom document property. You can add a new document property only to the custom DocumentProperties collection.

Syntax

expression .Add(Name, LinkToContent, Type, Value, LinkSource)

expression Required. A variable that represents a DocumentProperties object. The custom DocumentProperties object.

Parameters

Name | Required/Optional | Data Type | Description
Name | Required | String | The name of the property.
LinkToContent | Required | Boolean | Specifies whether the property is linked to the contents of the container document. If this argument is True, the LinkSource argument is required; if it's False, the value argument is required.
Type | Optional | Variant | The data type of the property. Can be one of the following MsoDocProperties constants: msoPropertyBoolean, msoPropertyDate, msoPropertyFloat, msoPropertyNumber, or msoPropertyString.
Value | Optional | Variant | The value of the property, if it's not linked to the contents of the container document. The value is converted to match the data type specified by the Type argument, and if it can't be converted, an error occurs. If LinkToContent is True, the argument is ignored and the new document property is assigned a default value until the linked property values are updated by the container application (usually when the document is saved).
LinkSource | Optional | Variant | Ignored if LinkToContent is False. The source of the linked property. The container application determines what types of source linking you can use.

Remarks

If you add a custom document property to the DocumentProperties collection that's linked to a given value in a Microsoft Office document, you must save the document to see the change to the DocumentProperty object.

Example

This example, which is designed to run in Microsoft Word, adds three custom document properties to the DocumentProperties collection.

VBA Copy code Copy code
With ActiveDocument.CustomDocumentProperties
    .Add Name:="CustomNumber", _
        LinkToContent:=False, _
        Type:=msoPropertyTypeNumber, _
        Value:=1000
    .Add Name:="CustomString", _
        LinkToContent:=False, _
        Type:=msoPropertyTypeString, _
        Value:="This is a custom property."
    .Add Name:="CustomDate", _
        LinkToContent:=False, _
        Type:=msoPropertyTypeDate, _
        Value:=Date
End With

See also

Concepts

DocumentProperties Object

Other resources

DocumentProperties Object Members


DocumentProperty Object (Office)

 Copy code hover
[image]

DocumentProperty Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a custom or built-in document property of a container document. The DocumentProperty object is a member of the DocumentProperties collection.

Remarks

Use the Microsoft Word Document.BuiltinDocumentProperties(index) property, where index is the name or index number of the built-in document property, to return a single DocumentProperty object that represents a specific built-in document property. Use the Microsoft Word Document.CustomDocumentProperties(index) property, where index is the name or index number of the custom document property, to return a DocumentProperty object that represents a specific custom document property. The following list contains the names of all the available built-in document properties:

Note Note

Properties of type msoPropertyTypeString are limited in length to 255 characters.

See also

Concepts

Object Model Reference

Other resources

DocumentProperty Object Members


DocumentProperty Members (Office)

 Copy code hover
[image]

DocumentProperty Members (Office)
Send feedback

Published: July 09, 2012

Represents a custom or built-in document property of a container document. The DocumentProperty object is a member of the DocumentProperties collection.

Methods

Name | Description
Delete | Removes a custom document property.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the DocumentProperty object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentProperty object was created. Read-only.
LinkSource | Gets or sets the source of a linked custom document property. Read/write.
LinkToContent | Is True if the value of the custom document property is linked to the content of the container document. False if the value is static. Read/write.
Name | Gets or sets the name of a document property. Read/write.
Parent | Gets the Parent object for the DocumentProperty object. Read-only.
Type | Gets or sets the document property type. Read-only for built-in document properties; read/write for custom document properties.
Value | Gets or sets the value of a document property. Read/write.


DocumentProperty Properties (Office)

 Copy code hover
[image]

DocumentProperty Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the DocumentProperty object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the DocumentProperty object was created. Read-only.
LinkSource | Gets or sets the source of a linked custom document property. Read/write.
LinkToContent | Is True if the value of the custom document property is linked to the content of the container document. False if the value is static. Read/write.
Name | Gets or sets the name of a document property. Read/write.
Parent | Gets the Parent object for the DocumentProperty object. Read-only.
Type | Gets or sets the document property type. Read-only for built-in document properties; read/write for custom document properties.
Value | Gets or sets the value of a document property. Read/write.


DocumentProperty.Application Property (Office)

 Copy code hover
[image]

DocumentProperty.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the DocumentProperty object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application(ppidisp)

expression A variable that represents a DocumentProperty object.

Parameters

Name | Required/Optional | Data Type | Description
ppidisp | Required | Object | Represents the identifier for a document property.

Return Value

[HRESULT]

See also

Concepts

DocumentProperty Object

Other resources

DocumentProperty Object Members


DocumentProperty.Creator Property (Office)

 Copy code hover
[image]

DocumentProperty.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the DocumentProperty object was created. Read-only.

Syntax

expression .Creator(plCreator)

expression A variable that represents a DocumentProperty object.

Parameters

Name | Required/Optional | Data Type | Description
plCreator | Required | Long | The name or index number of the built-in document property.

Return Value

[HRESULT]

See also

Concepts

DocumentProperty Object

Other resources

DocumentProperty Object Members


DocumentProperty.LinkSource Property (Office)

 Copy code hover
[image]

DocumentProperty.LinkSource Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the source of a linked custom document property. Read/write.

Syntax

expression .LinkSource(pbstrSourceRetVal)

expression A variable that represents a DocumentProperty object.

Parameters

Name | Required/Optional | Data Type | Description
pbstrSourceRetVal | Required | String | Represents the name of the source of the document property.

Remarks

This property applies only to custom document properties; you cannot use it with built-in document properties.

The source of the specified link is defined by the container application.

Setting the LinkSource property sets the LinkToContent property to True.

Example

This example displays the linked status of a custom document property. For the example to work, dp must be a valid DocumentProperty object.

Copy code Copy code
Sub DisplayLinkStatus(dp As DocumentProperty)
 Dim stat As String, tf As String
 If dp.LinkToContent Then
 tf = ""
 Else
 tf = "not "
 End If
 stat = "This property is " & tf & "linked"
 If dp.LinkToContent Then
 stat = stat + Chr(13) & "The link source is " & dp.LinkSource
 End If
 MsgBox stat
End Sub

See also

Concepts

DocumentProperty Object

Other resources

DocumentProperty Object Members


DocumentProperty.LinkToContent Property (Office)

 Copy code hover
[image]

DocumentProperty.LinkToContent Property (Office)
See also Send feedback

Published: July 09, 2012

Is True if the value of the custom document property is linked to the content of the container document. False if the value is static. Read/write.

Syntax

expression .LinkToContent(pfLinkRetVal)

expression A variable that represents a DocumentProperty object.

Parameters

Name | Required/Optional | Data Type | Description
pfLinkRetVal | Required | Boolean | Indicates whether the document property is linked to the container document.

Remarks

This property applies only to custom document properties. For built-in document properties, the value of this property is False.

Use the LinkSource property to set the source for the specified linked property. Setting the LinkSource property sets the LinkToContent property to True.

Example

This example displays the linked status of the custom document property. For the example to work, dp must be a valid DocumentProperty object.

Copy code Copy code
Sub DisplayLinkStatus(dp As DocumentProperty)
 Dim stat As String, tf As String
 If dp.LinkToContent Then
 tf = ""
 Else
 tf = "not "
 End If
 stat = "This property is " & tf & "linked"
 If dp.LinkToContent Then
 stat = stat + Chr(13) & "The link source is " & dp.LinkSource
 End If
 MsgBox stat
End Sub

See also

Concepts

DocumentProperty Object
Sync Object

Other resources

DocumentProperty Object Members
Sync Object Members


DocumentProperty.Name Property (Office)

 Copy code hover
[image]

DocumentProperty.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the name of a document property. Read/write.

Syntax

expression .Name(lcid, pbstrRetVal)

expression A variable that represents a DocumentProperty object.

Parameters

Name | Required/Optional | Data Type | Description
lcid | Required | Long | Represents the language identifier.
pbstrRetVal | Required | String | Represents the return value for the property.

Return Value

String

Remarks

A DocumentProperty object represents a custom or built-in document property of a container document.

Example

This example displays the name, type, and value of a document property. You must pass a valid DocumentProperty object to the procedure.

Copy code Copy code
Sub DisplayPropertyInfo(dp As DocumentProperty)
 MsgBox "value = " & dp.Value & Chr(13) & _
 "type = " & dp.Type & Chr(13) & _
 "name = " & dp.Name
End Sub

See also

Concepts

DocumentProperty Object

Other resources

DocumentProperty Object Members


DocumentProperty.Parent Property (Office)

 Copy code hover
[image]

DocumentProperty.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the DocumentProperty object. Read-only.

Syntax

expression .Parent

expression A variable that represents a DocumentProperty object.

Return Value

Object

Example

This example displays the name of the parent object for a document property. You must pass a valid DocumentProperty object to the procedure.

VBA Copy code Copy code
Sub DisplayParent(dp as DocumentProperty)
 MsgBox dp.Parent.Name
End Sub

See also

Concepts

DocumentProperty Object

Other resources

DocumentProperty Object Members


DocumentProperty.Type Property (Office)

 Copy code hover
[image]

DocumentProperty.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the document property type. Read-only for built-in document properties; read/write for custom document properties.

Syntax

expression .Type

expression Required. A variable that represents a DocumentProperty object.

Remarks

The return value will be a MsoDocProperties constant.

See also

Concepts

DocumentProperty Object

Other resources

DocumentProperty Object Members


DocumentProperty.Value Property (Office)

 Copy code hover
[image]

DocumentProperty.Value Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the value of a document property. Read/write.

Syntax

expression .Value

expression Required. A variable that represents a DocumentProperty object.

Remarks

If the container application doesn't define a value for one of the built-in document properties, reading the Value property for that document property causes an error.

See also

Concepts

DocumentProperty Object

Other resources

DocumentProperty Object Members


DocumentProperty Methods (Office)

 Copy code hover
[image]

DocumentProperty Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Removes a custom document property.


DocumentProperty.Delete Method (Office)

 Copy code hover
[image]

DocumentProperty.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Removes a custom document property.

Syntax

expression .Delete

expression Required. A variable that represents a DocumentProperty object.

Remarks

You cannot delete a built-in document property.

Example

This example deletes a custom document property. For this example to run properly, you must have a custom DocumentProperty object named "CustomNumber".

VBA Copy code Copy code
ActiveDocument.CustomDocumentProperties("CustomNumber").Delete

See also

Concepts

DocumentProperty Object

Other resources

DocumentProperty Object Members


EffectParameter Object (Office)

 Copy code hover
[image]

EffectParameter Object (Office)
See also Send feedback

Published: July 09, 2012

Describes a single Picture Effect parameter.

Version Information

Version Added: Office 2010

Remarks

Picture Effects are processed as a chain composed of individual items which are applied in sequence to create the final composited image. An Effects chain will allow an effect to be added to the chain, reordered, or removed from the chain. Effect Parameters specify properties of those effects.

Example

The following code sets several Picture Effect fill properties on a shape in a Microsoft PowerPoint slide.

VBA Copy code Copy code
Sub PictureEffectSample()
' Setup a slide with one picture shape.
With ActivePresentation.Slides(1).Shapes(1).Fill.PictureEffects

 ' Insert a 150% Saturation effect.
 .Insert(msoEffectSaturation).EffectParameters(1).Value = 1.5

 ' Insert Brightness/Contrast effect and set values to -50% Brightness and +25% Contrast.
 Dim brightnessContrast As PictureEffect
 Set brightnessContrast = .Insert(msoEffectBrightnessContrast)
 brightnessContrast.EffectParameters(1).Value = -0.5
 brightnessContrast.EffectParameters(2).Value = 0.25

 ' Remove all Picture effects.
 While .Count > 0
 .Delete (1)
 Wend

End With
End Sub

See also

Concepts

Object Model Reference

Other resources

EffectParameter Object Members


EffectParameter Members (Office)

 Copy code hover
[image]

EffectParameter Members (Office)
Send feedback

Published: July 09, 2012

Describes a single Picture Effect parameter.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the EffectParameter object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the EffectParameter object was created. Read-only
Name | Retrieves the string name of the EffectParameter parameter. Read-only
Value | Retrieves or sets the value of the EffectParameter object. Read/write


EffectParameter Properties (Office)

 Copy code hover
[image]

EffectParameter Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the EffectParameter object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the EffectParameter object was created. Read-only
Name | Retrieves the string name of the EffectParameter parameter. Read-only
Value | Retrieves or sets the value of the EffectParameter object. Read/write


EffectParameter.Application Property (Office)

 Copy code hover
[image]

EffectParameter.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the EffectParameter object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a EffectParameter object.

See also

Concepts

EffectParameter Object

Other resources

EffectParameter Object Members


EffectParameter.Creator Property (Office)

 Copy code hover
[image]

EffectParameter.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the EffectParameter object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a EffectParameter object.

See also

Concepts

EffectParameter Object

Other resources

EffectParameter Object Members


EffectParameter.Name Property (Office)

 Copy code hover
[image]

EffectParameter.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the string name of the EffectParameter parameter. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Name

expression An expression that returns a EffectParameter object.

See also

Concepts

EffectParameter Object

Other resources

EffectParameter Object Members


EffectParameter.Value Property (Office)

 Copy code hover
[image]

EffectParameter.Value Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves or sets the value of the EffectParameter object. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Value

expression An expression that returns a EffectParameter object.

Example

The following code sets the first parameter of the PictureEffect object as color temperature.

VBA Copy code Copy code
Dim picEffect As PictureEffect

picEffect.EffectParameters(1).Value = MsoPictureEffectType.msoEffectColorTemperature

See also

Concepts

EffectParameter Object

Other resources

EffectParameter Object Members


EffectParameters Object (Office)

 Copy code hover
[image]

EffectParameters Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of EffectParameter objects.

Version Information

Version Added: Office 2010

Remarks

Picture Effects are processed as a chain composed of individual items which are applied in sequence to create the final composited image. An Effects chain will allow an effect to be added to the chain, reordered, or removed from the chain. Effect Parameters specify properties of those effects.

Example

The following code sets several Picture Effect fill properties on a shape in a Microsoft PowerPoint slide.

VBA Copy code Copy code
Sub PictureEffectSample()
' Setup a slide with one picture shape.
With ActivePresentation.Slides(1).Shapes(1).Fill.PictureEffects

 ' Insert a 150% Saturation effect.
 .Insert(msoEffectSaturation).EffectParameters(1).Value = 1.5

 ' Insert Brightness/Contrast effect and set values to -50% Brightness and +25% Contrast.
 Dim brightnessContrast As PictureEffect
 Set brightnessContrast = .Insert(msoEffectBrightnessContrast)
 brightnessContrast.EffectParameters(1).Value = -0.5
 brightnessContrast.EffectParameters(2).Value = 0.25

 ' Remove all Picture effects.
 While .Count > 0
 .Delete (1)
 Wend

End With
End Sub

See also

Concepts

Object Model Reference

Other resources

EffectParameters Object Members


EffectParameters Members (Office)

 Copy code hover
[image]

EffectParameters Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of EffectParameter objects.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the EffectParameters object. Read-only
Count | Retrieves the count of the number of EffectParameter objects contained within the EffectParameters collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the EffectParameters object was created. Read-only
Item | Retrieves a EffectParameter object at the specified index or with the specified unique Id. Read-only


EffectParameters Properties (Office)

 Copy code hover
[image]

EffectParameters Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the EffectParameters object. Read-only
Count | Retrieves the count of the number of EffectParameter objects contained within the EffectParameters collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the EffectParameters object was created. Read-only
Item | Retrieves a EffectParameter object at the specified index or with the specified unique Id. Read-only


EffectParameters.Application Property (Office)

 Copy code hover
[image]

EffectParameters.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the EffectParameters object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a EffectParameters object.

See also

Concepts

EffectParameters Object

Other resources

EffectParameters Object Members


EffectParameters.Count Property (Office)

 Copy code hover
[image]

EffectParameters.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the count of the number of EffectParameter objects contained within the EffectParameters collection. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Count

expression An expression that returns a EffectParameters object.

See also

Concepts

EffectParameters Object

Other resources

EffectParameters Object Members


EffectParameters.Creator Property (Office)

 Copy code hover
[image]

EffectParameters.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the EffectParameters object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a EffectParameters object.

See also

Concepts

EffectParameters Object

Other resources

EffectParameters Object Members


EffectParameters.Item Property (Office)

 Copy code hover
[image]

EffectParameters.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves a EffectParameter object at the specified index or with the specified unique Id. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Item(Index)

expression An expression that returns a EffectParameters object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | Specifies either an integer representing the index or a string representing the location of the EffectParameter.

See also

Concepts

EffectParameters Object

Other resources

EffectParameters Object Members


EncryptionProvider Object (Office)

 Copy code hover
[image]

EncryptionProvider Object (Office)
See also Send feedback

Published: July 09, 2012

Provides the methods for setting up permissions, applying the cryptography of the underlying encryption and decryption, and user authentication.

Remarks

Encryption providers are implemented through custom COM add-ins. You are provided with storage within Office documents for add-in specific information to store whatever information you need to encrypt, decrypt, apply rights, and display permission setup or authentication user interfaces.

See also

Concepts

Object Model Reference

Other resources

EncryptionProvider Object Members


EncryptionProvider Members (Office)

 Copy code hover
[image]

EncryptionProvider Members (Office)
Send feedback

Published: July 09, 2012

Provides the methods for setting up permissions, applying the cryptography of the underlying encryption and decryption, and user authentication.

Methods

Name | Description
Authenticate | Used to determine whether the user has the proper permissions to open the encrypted document.
CloneSession | Creates a second, working copy of the EncryptionProvider object's encryption session for a file that is about to be saved.
DecryptStream | Decrypts and returns a stream of encrypted data for a document.
EncryptStream | Encrypts and returns a stream of data for a document.
EndSession | Ends the current encryption session.
GetProviderDetail | Displays information about the encryption of the current document.
NewSession | Used by the EncryptionProvider object to create a new encryption session. This session is used by the provider to cache document-specific information about the encryption, users, and rights while the document is in memory.
Save | Saves an encrypted document.
ShowSettings | Used to display a dialog of the encryption settings for the current document.


EncryptionProvider Methods (Office)

 Copy code hover
[image]

EncryptionProvider Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Authenticate | Used to determine whether the user has the proper permissions to open the encrypted document.
CloneSession | Creates a second, working copy of the EncryptionProvider object's encryption session for a file that is about to be saved.
DecryptStream | Decrypts and returns a stream of encrypted data for a document.
EncryptStream | Encrypts and returns a stream of data for a document.
EndSession | Ends the current encryption session.
GetProviderDetail | Displays information about the encryption of the current document.
NewSession | Used by the EncryptionProvider object to create a new encryption session. This session is used by the provider to cache document-specific information about the encryption, users, and rights while the document is in memory.
Save | Saves an encrypted document.
ShowSettings | Used to display a dialog of the encryption settings for the current document.


EncryptionProvider.Authenticate Method (Office)

 Copy code hover
[image]

EncryptionProvider.Authenticate Method (Office)
See also Send feedback

Published: July 09, 2012

Used to determine whether the user has the proper permissions to open the encrypted document.

Syntax

expression .Authenticate(ParentWindow, EncryptionData, PermissionsMask)

expression An expression that returns a EncryptionProvider object.

Parameters

Name | Required/Optional | Data Type | Description
ParentWindow | Required | IUnknown | Specifies the window that is called to display the encryption settings.
EncryptionData | Required | IUnknown | Contains the encrypted data for the current document.
PermissionsMask | Required | Unsigned Integer | The user interface displayed by the encryption provider add-in.

Return Value

Long

Remarks

This is where your COM add-in encryption provider displays whatever user interface is applicable for applying encryption. For example, a password encryption provider would prompt for the user's password.

See also

Concepts

EncryptionProvider Object

Other resources

EncryptionProvider Object Members


EncryptionProvider.CloneSession Method (Office)

 Copy code hover
[image]

EncryptionProvider.CloneSession Method (Office)
See also Send feedback

Published: July 09, 2012

Creates a second, working copy of the EncryptionProvider object's encryption session for a file that is about to be saved.

Syntax

expression .CloneSession(SessionHandle)

expression An expression that returns a EncryptionProvider object.

Parameters

Name | Required/Optional | Data Type | Description
SessionHandle | Required | Long | The ID of the cloned session.

Return Value

Long

Remarks

The output of this method is another session handle with the same encryption settings. When an autoSave operation occurs, you are provided with this session handle.

See also

Concepts

EncryptionProvider Object

Other resources

EncryptionProvider Object Members


EncryptionProvider.DecryptStream Method (Office)

 Copy code hover
[image]

EncryptionProvider.DecryptStream Method (Office)
See also Send feedback

Published: July 09, 2012

Decrypts and returns a stream of encrypted data for a document.

Syntax

expression .DecryptStream(SessionHandle, StreamName, EncryptedStream, UnencryptedStream)

expression An expression that returns a EncryptionProvider object.

Parameters

Name | Required/Optional | Data Type | Description
SessionHandle | Required | Long | The ID of the current session.
StreamName | Required | String | The ID of the stream of data.
EncryptedStream | Required | IUnknown | The encrypted data stream.
UnencryptedStream | Required | IUnknown | The data stream before dencryption.

Remarks

This method is called by your COM add-in when the document is opened, and after your add-in has verified that the user opening the document is authenticated. This method is the inverse of EncryptStream method and converts encrypted data back into pure (un-encrypted) data.

See also

Concepts

EncryptionProvider Object

Other resources

EncryptionProvider Object Members


EncryptionProvider.EncryptStream Method (Office)

 Copy code hover
[image]

EncryptionProvider.EncryptStream Method (Office)
See also Send feedback

Published: July 09, 2012

Encrypts and returns a stream of data for a document.

Syntax

expression .EncryptStream(SessionHandle, StreamName, UnencryptedStream, EncryptedStream)

expression An expression that returns a EncryptionProvider object.

Parameters

Name | Required/Optional | Data Type | Description
SessionHandle | Required | Long | The ID of the current session.
StreamName | Required | String | The name of the encrypted stream of document data.
UnencryptedStream | Required | IUnknown | The data stream before encryption.
EncryptedStream | Required | IUnknown | The data stream information after it has been encrypted.

Remarks

This method is typically called by your COM add-in during a save operation.

See also

Concepts

EncryptionProvider Object

Other resources

EncryptionProvider Object Members


EncryptionProvider.EndSession Method (Office)

 Copy code hover
[image]

EncryptionProvider.EndSession Method (Office)
See also Send feedback

Published: July 09, 2012

Ends the current encryption session.

Syntax

expression .EndSession(SessionHandle)

expression An expression that returns a EncryptionProvider object.

Parameters

Name | Required/Optional | Data Type | Description
SessionHandle | Required | Long | The ID of the current session.

Remarks

During a save operation, the CloneSession method is called by your COM add-in to create a second, working copy of the EncryptionProvider object's encryption session for the file that is about to be saved. Next the Save method is called to get whatever custom information you would like to persist about your encryption settings. This information is available when this document is reopened later. Then the EncryptStream method is called which gives the provider the entire contents of the document. And finally, to complete the process, the EndSession method for the cloned session handle.

See also

Concepts

EncryptionProvider Object

Other resources

EncryptionProvider Object Members


EncryptionProvider.GetProviderDetail Method (Office)

 Copy code hover
[image]

EncryptionProvider.GetProviderDetail Method (Office)
See also Send feedback

Published: July 09, 2012

Displays information about the encryption of the current document.

Syntax

expression .GetProviderDetail(encprovdet)

expression An expression that returns a EncryptionProvider object.

Parameters

Name | Required/Optional | Data Type | Description
encprovdet | Required | EncryptionProviderDetail | Specifies the encryption information that you want.

Return Value

Variant

Remarks

This method allows you to query the EncryptionProvider object for information such as what is the download URL for users without your custom COM add-in installed, what algorithm are you implementing, and what cipher mode you are using.

See also

Concepts

EncryptionProvider Object

Other resources

EncryptionProvider Object Members


EncryptionProvider.NewSession Method (Office)

 Copy code hover
[image]

EncryptionProvider.NewSession Method (Office)
See also Send feedback

Published: July 09, 2012

Used by the EncryptionProvider object to create a new encryption session. This session is used by the provider to cache document-specific information about the encryption, users, and rights while the document is in memory.

Syntax

expression .NewSession(ParentWindow)

expression An expression that returns a EncryptionProvider object.

Parameters

Name | Required/Optional | Data Type | Description
ParentWindow | Required | IUnknown | Specifies the window that is called to display the encryption settings.

Return Value

Long

Remarks

This method is called by your COM add-in.

See also

Concepts

EncryptionProvider Object

Other resources

EncryptionProvider Object Members


EncryptionProvider.Save Method (Office)

 Copy code hover
[image]

EncryptionProvider.Save Method (Office)
See also Send feedback

Published: July 09, 2012

Saves an encrypted document.

Syntax

expression .Save(SessionHandle, EncryptionData)

expression An expression that returns a EncryptionProvider object.

Parameters

Name | Required/Optional | Data Type | Description
SessionHandle | Required | Long | The ID of the current session.
EncryptionData | Required | IUnknown | Contains the encryption information.

Return Value

Long

Remarks

When you save a file to the Office Open XML File Format (which is the only format that supports custom file encryption), then the provider is called by your COM add-in to encrypt the document. If you attempt to save to a format that does not support custom file encryption and you have the appropriate rights to do so, then Microsoft Office will save the document without encryption. This allows documents to be exported to formats that do not support encryption or rights management.

See also

Concepts

EncryptionProvider Object

Other resources

EncryptionProvider Object Members


EncryptionProvider.ShowSettings Method (Office)

 Copy code hover
[image]

EncryptionProvider.ShowSettings Method (Office)
See also Send feedback

Published: July 09, 2012

Used to display a dialog of the encryption settings for the current document.

Syntax

expression .ShowSettings(SessionHandle, ParentWindow, ReadOnly, Remove)

expression An expression that returns a EncryptionProvider object.

Parameters

Name | Required/Optional | Data Type | Description
SessionHandle | Required | Long | The ID of the current session.
ParentWindow | Required | IUnknown | Specifies the window that is called to display the encryption settings.
ReadOnly | Required | Boolean | Specifies whether you want the user to be able to change the encryption settings.
Remove | Required | Boolean | If True the encryption for a document will be removed during the next save operation.

Remarks

This method can only be called on an already encrypted document. You can use this method in your COM add-in to display whatever user experience you like based on the user'smissions. For example, in a pure encryption scenario, you can display a dialog box to change the document's password. In a rights management scenario, you can decide whether to show a dialog box for changing permissions or show the user's permissions.

See also

Concepts

EncryptionProvider Object

Other resources

EncryptionProvider Object Members


FileDialog Object (Office)

 Copy code hover
[image]

FileDialog Object (Office)
See also Send feedback

Published: July 09, 2012

Provides file dialog box functionality similar to the functionality of the standard Open and Save dialog boxes found in Microsoft Office applications.

Remarks

Use the FileDialog property to return a FileDialog object. The FileDialog property is located in each individual Office application's Application object. The property takes a single argument, DialogType, that determines the type of FileDialog object that the property returns. There are four types of FileDialog object:

  • Open dialog box - lets users select one or more files that you can then open in the host application using the Execute method.

  • SaveAs dialog box - lets users select a single file that you can then save the current file as using the Execute method.

  • File Picker dialog box - lets users select one or more files. The file paths that the user selects are captured in the FileDialogSelectedItems collection.

  • Folder Picker dialog box - lets users select a path. The path that the user selects is captured in the FileDialogSelectedItems collection.

Each host application can only create a single instance of the FileDialog object. Therefore, many of the properties of the FileDialog object persist even when you create multiple FileDialog objects. Therefore, make sure that you set all of the properties appropriately for your purpose before you display the dialog box.

Example

To display a file dialog box using the FileDialog object, you must use the Show method. Once a dialog box is displayed, no code executes until the user dismisses the dialog box. The following example creates and displays a File Picker dialog box and then displays each selected file in a message box.

Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialog object.
 Dim fd As FileDialog

 'Create a FileDialog object as a File Picker dialog box.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,
 'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant

 'Use a With...End With block to reference the FileDialog object.
 With fd

 'Use the Show method to display the File Picker dialog box and return the user's action.
 'The user pressed the button.
 If .Show = -1 Then

 'Step through each string in the FileDialogSelectedItems collection.
 For Each vrtSelectedItem In .SelectedItems

 'vrtSelectedItem is aString that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message box.
 MsgBox "The path is: " & vrtSelectedItem

 Next vrtSelectedItem
 'The user pressed Cancel.
 Else
 End If
 End With

 'Set the object variable to Nothing.
 Set fd = Nothing

End Sub

See also

Concepts

Object Model Reference

Other resources

FileDialog Object Members


FileDialog Members (Office)

 Copy code hover
[image]

FileDialog Members (Office)
Send feedback

Published: July 09, 2012

Provides file dialog box functionality similar to the functionality of the standard Open and Save dialog boxes found in Microsoft Office applications.

Methods

Name | Description
Execute | Carries out a user's action right after the Show method is invoked.
Show | Displays a file dialog box and returns a Long indicating whether the user pressed the Action button (-1) or the Cancel button (0). When you call the Show method, no more code executes until the user dismisses the file dialog box. In the case of Open and SaveAs dialog boxes, use the Execute method right after the Show method to carry out the user's action.

Properties

Name | Description
AllowMultiSelect | Is True if the user is allowed to select multiple files from a file dialog box. Read/write.
Application | Gets an Application object that represents the container application for the FileDialog object (you can use this property with an Automation object to return that object's container application). Read-only.
ButtonName | Sets or gets a String representing the text that is displayed on the action button of a file dialog box. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the FileDialog object was created. Read-only.
DialogType | Gets an MsoFileDialogType constant representing the type of file dialog box that the FileDialog object is set to display. Read-only.
FilterIndex | Gets or sets a Long indicating the default file filter of a file dialog box. The default filter determines which types of files are displayed when the file dialog box is first opened. Read/write.
Filters | Gets a FileDialogFilters collection. Read-only.
InitialFileName | Set or returns a String representing the path or file name that is initially displayed in a file dialog box. Read/write.
InitialView | Gets or sets an MsoFileDialogView constant representing the initial presentation of files and folders in a file dialog box. Read/write.
Item | Gets the text associated with an object. Read-only.
Parent | Gets the Parent object for the FileDialog object. Read-only.
SelectedItems | Gets a FileDialogSelectedItems collection. This collection contains a list of the paths of the files that a user selected from a file dialog box displayed using the Show method of the FileDialog object. Read-only.
Title | Sets or gets the title of a file dialog box displayed using the FileDialog object. Read/write.


FileDialog Properties (Office)

 Copy code hover
[image]

FileDialog Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
AllowMultiSelect | Is True if the user is allowed to select multiple files from a file dialog box. Read/write.
Application | Gets an Application object that represents the container application for the FileDialog object (you can use this property with an Automation object to return that object's container application). Read-only.
ButtonName | Sets or gets a String representing the text that is displayed on the action button of a file dialog box. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the FileDialog object was created. Read-only.
DialogType | Gets an MsoFileDialogType constant representing the type of file dialog box that the FileDialog object is set to display. Read-only.
FilterIndex | Gets or sets a Long indicating the default file filter of a file dialog box. The default filter determines which types of files are displayed when the file dialog box is first opened. Read/write.
Filters | Gets a FileDialogFilters collection. Read-only.
InitialFileName | Set or returns a String representing the path or file name that is initially displayed in a file dialog box. Read/write.
InitialView | Gets or sets an MsoFileDialogView constant representing the initial presentation of files and folders in a file dialog box. Read/write.
Item | Gets the text associated with an object. Read-only.
Parent | Gets the Parent object for the FileDialog object. Read-only.
SelectedItems | Gets a FileDialogSelectedItems collection. This collection contains a list of the paths of the files that a user selected from a file dialog box displayed using the Show method of the FileDialog object. Read-only.
Title | Sets or gets the title of a file dialog box displayed using the FileDialog object. Read/write.


FileDialog.AllowMultiSelect Property (Office)

 Copy code hover
[image]

FileDialog.AllowMultiSelect Property (Office)
See also Send feedback

Published: July 09, 2012

Is True if the user is allowed to select multiple files from a file dialog box. Read/write.

Syntax

expression .AllowMultiSelect

expression A variable that represents a FileDialog object.

Remarks

This property has no effect on Folder Picker dialog boxes or SaveAs dialog boxes because users should never be able to select multiple files in these types of file dialog boxes.

Example

The following example displays a File Picker dialog box using the FileDialog object and displays each selected file in a message box.

Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialog object.
 Dim fd As FileDialog

 'Create a FileDialog object as a File Picker dialog box.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,
 'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant

 'Use a With...End With block to reference the FileDialog object.
 With fd

 'Allow the selection of multiple files.
 .AllowMultiSelect = True

 'Use the Show method to display the file picker dialog and return the user's action.
 'If the user presses the button...
 If .Show = -1 Then

 'Step through each string in the FileDialogSelectedItems collection.
 For Each vrtSelectedItem In .SelectedItems

 'vrtSelectedItem is aString that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message box.
 MsgBox "Selected item's path: " & vrtSelectedItem

 Next
 'If the user presses Cancel...
 Else
 End If
 End With

 'Set the object variable to Nothing.
 Set fd = Nothing

End Sub

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.Application Property (Office)

 Copy code hover
[image]

FileDialog.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the FileDialog object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a FileDialog object.

Return Value

Object

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.ButtonName Property (Office)

 Copy code hover
[image]

FileDialog.ButtonName Property (Office)
See also Send feedback

Published: July 09, 2012

Sets or gets a String representing the text that is displayed on the action button of a file dialog box. Read/write.

Syntax

expression .ButtonName

expression A variable that represents a FileDialog object.

Remarks

By default, this property is set to the standard text for the type of file dialog box. For example, in the case of the Open dialog box, the property is set to "Open" by default. This string is limited to fifty-one characters.

Example

The following example displays a File Picker dialog box using the FileDialog object and displays each selected file in a message box.

Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialog object.
 Dim fd As FileDialog

 'Create a FileDialog object as a File Picker dialog box.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,
 'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant

 'Use a With...End With block to reference the FileDialog object.
 With fd

 'Change the text on the button.
 .ButtonName = "Archive"

 'Use the Show method to display the File Picker dialog box and return the user's action.
 'If the user presses the button...
 If .Show = -1 Then

 'Step through eachString in the FileDialogSelectedItems collection.
 For Each vrtSelectedItem In .SelectedItems

 'vrtSelectedItem is aString that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message box.
 MsgBox "Selected item's path: " & vrtSelectedItem

 Next vrtSelectedItem
 'If the user presses Cancel...
 Else
 End If
 End With

 'Set the object variable to Nothing.
 Set fd = Nothing

End Sub

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.Creator Property (Office)

 Copy code hover
[image]

FileDialog.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the FileDialog object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a FileDialog object.

Return Value

Long

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.DialogType Property (Office)

 Copy code hover
[image]

FileDialog.DialogType Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an MsoFileDialogType constant representing the type of file dialog box that the FileDialog object is set to display. Read-only.

Syntax

expression .DialogType

expression A variable that represents a FileDialog object.

Example

The following example takes a FileDialog object of an unknown type and runs the Execute method if it is a SaveAs dialog box or an Open dialog box.

Copy code Copy code
Sub DisplayAndExecuteFileDialog(ByRef fd As FileDialog)

 'Use a With...End With block to reference the FileDialog object.
 With fd
 'If the user presses the action button...
 If .Show = -1 Then

 'Use the DialogType property to determine whether to
 'use the Execute method.
 Select Case .DialogType
 Case msoFileDialogOpen, msoFileDialogSaveAs: .Execute
 'Do nothing otherwise.
 Case Else
 End Select
 'If the user presses Cancel...
 Else
 End If
 End With

End Sub

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.FilterIndex Property (Office)

 Copy code hover
[image]

FileDialog.FilterIndex Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a Long indicating the default file filter of a file dialog box. The default filter determines which types of files are displayed when the file dialog box is first opened. Read/write.

Syntax

expression .FilterIndex

expression A variable that represents a FileDialog object.

Remarks

If you try to set this property to a number greater than the number of filters, the last available filter will be selected.

Example

The following example displays a File Picker dialog box using the FileDialog object and displays each selected file in a message box. This example also demonstrates how to add a new file filter and how to make it the default filter.

Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialog object.
 Dim fd As FileDialog

 'Create a FileDialog object as a File Picker dialog box.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,
 'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant

 'Use a With...End With block to reference the FileDialog object.
 With fd

 'Add a filter that includes GIF and JPEG images and make it the second item in the list.
 .Filters.Add "Images", "*.gif; *.jpg; *.jpeg", 2

 'Sets the initial file filter to number 2.
 .FilterIndex = 2

 'Use the Show method to display the File Picker dialog box and return the user's action.
 'If the user presses the button...
 If .Show = -1 Then

 'Step through each string in the FileDialogSelectedItems collection.
 For Each vrtSelectedItem In .SelectedItems

 'vrtSelectedItem is aString that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message box.
 MsgBox "Selected item's path: " & vrtSelectedItem

 Next vrtSelectedItem
 'If the user presses Cancel...
 Else
 End If
 End With

 'Set the object variable to Nothing.
 Set fd = Nothing

End Sub

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.Filters Property (Office)

 Copy code hover
[image]

FileDialog.Filters Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a FileDialogFilters collection. Read-only.

Syntax

expression .Filters

expression A variable that represents a FileDialog object.

Return Value

FileDialogFilters

Example

The following example displays a File Picker dialog box using the FileDialog object and displays each selected file in a message box. The example also adds a new file filter called "Images."

VBA Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialog object.
 Dim fd As FileDialog

 'Create a FileDialog object as a File Picker dialog.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,
 'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant

 'Use a With...End With block to reference the FileDialog object.
 With fd

 'Add a filter that includes GIF and JPEG images and make it the first item in the list.
 .Filters.Add "Images", "*.gif; *.jpg; *.jpeg", 1

 'Use the Show method to display the File Picker dialog box and return the user's action.
 'If the user presses the button...
 If .Show = -1 Then

 'Step through each string in the FileDialogSelectedItems collection.
 For Each vrtSelectedItem In .SelectedItems

 'vrtSelectedItem is aString that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message box.
 MsgBox "Selected item's path: " & vrtSelectedItem

 Next vrtSelectedItem
 'If the user presses Cancel...
 Else
 End If
 End With

 'Set the object variable to Nothing.
 Set fd = Nothing

End Sub

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.InitialFileName Property (Office)

 Copy code hover
[image]

FileDialog.InitialFileName Property (Office)
See also Send feedback

Published: July 09, 2012

Set or returns a String representing the path or file name that is initially displayed in a file dialog box. Read/write.

Syntax

expression .InitialFileName

expression A variable that represents a FileDialog object.

Remarks

You can use the '*' and '?' wildcard characters when specifying the file name but not when specifying the path. The '*' symbol represents any number of consecutive characters and the '?' represents a single character. For example, .InitialFileName = "c:\c*s.txt" returns both "charts.txt" and "checkregister.txt."

If you specify a path and no file name, then all files that are allowed by the file filter appear in the dialog box.

If you specify a file that exists in the initial folder, then only that file appears in the dialog box.

If you specify a file name that does not exist in the initial folder, then the dialog box contains no files. The type of file that you specify in the InitialFileName property overrides the file filter settings.

If you specify an invalid path, the last-used path is used. A message warns users when an invalid path is used.

Setting this property to a string longer than 256 characters causes a run-time error.

Example

The following example displays a File Picker dialog box using the FileDialog object and displays each selected file in a message box.

VBA Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialog object
 Dim fd As FileDialog

 'Create a FileDialog object as a File Picker dialog box.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,
 'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant

 'Use a With...End With block to reference the FileDialog object.
 With fd

 'Set the initial path to the C:\ drive.
 .InitialFileName = "C:\"

 'Use the Show method to display the File Picker dialog box and return the user's action.
 'If the user presses the button...
 If .Show = -1 Then

 'Step through each string in the FileDialogSelectedItems collection.
 For Each vrtSelectedItem In .SelectedItems

 'vrtSelectedItem is aString that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message box.
 MsgBox "Selected item's path: " & vrtSelectedItem

 Next vrtSelectedItem
 'If the user presses Cancel...
 Else
 End If
 End With

 'Set the object variable to Nothing.
 Set fd = Nothing

End Sub

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.InitialView Property (Office)

 Copy code hover
[image]

FileDialog.InitialView Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets an MsoFileDialogView constant representing the initial presentation of files and folders in a file dialog box. Read/write.

Syntax

expression .InitialView

expression A variable that represents a FileDialog object.

Example

The following example displays a File Picker dialog box in details view using the FileDialog object and displays each selected file in a message box.

Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialog object.
 Dim fd As FileDialog

 'Create a FileDialog object as a File Picker dialog box.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,
 'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant

 'Use a With...End With block to reference the FileDialog object.
 With fd

 'Set the initial view to the details view.
 .InitialView = msoFileDialogViewDetails

 'Use the Show method to display the File Picker dialog box and return the user's action.
 'If the user presses the button...
 If .Show = -1 Then

 'Step through each string in the FileDialogSelectedItems collection.
 For Each vrtSelectedItem In .SelectedItems

 'vrtSelectedItem is aString that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message box.
 MsgBox "Selected item's path: " & vrtSelectedItem

 Next vrtSelectedItem
 'If the user presses Cancel...
 Else
 End If
 End With

 'Set the object variable to Nothing.
 Set fd = Nothing

End Sub

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.Item Property (Office)

 Copy code hover
[image]

FileDialog.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the text associated with an object. Read-only.

Syntax

expression .Item

expression Required. A variable that represents a FileDialog object.

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.Parent Property (Office)

 Copy code hover
[image]

FileDialog.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the FileDialog object. Read-only.

Syntax

expression .Parent

expression A variable that represents a FileDialog object.

Return Value

Object

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.SelectedItems Property (Office)

 Copy code hover
[image]

FileDialog.SelectedItems Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a FileDialogSelectedItems collection. This collection contains a list of the paths of the files that a user selected from a file dialog box displayed using the Show method of the FileDialog object. Read-only.

Syntax

expression .SelectedItems

expression A variable that represents a FileDialog object.

Example

The following example displays a File Picker dialog box using the FileDialog object and displays each selected file in a message box.

Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialog object.
 Dim fd As FileDialog

 'Create a FileDialog object as a File Picker dialog box.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,
 'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant

 'Use a With...End With block to reference the FileDialog object.
 With fd

 'Allow the user to select multiple files.
 .AllowMultiSelect = True

 'Use the Show method to display the File Picker dialog box and return the user's action.
 'If the user presses the button...
 If .Show = -1 Then
 'Step through each string in the FileDialogSelectedItems collection.
 For Each vrtSelectedItem In .SelectedItems

 'vrtSelectedItem is aString that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message box.
 MsgBox "Selected item's path: " & vrtSelectedItem

 Next
 'If the user presses Cancel...
 Else
 End If
 End With

 'Set the object variable to Nothing.
 Set fd = Nothing

End Sub

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.Title Property (Office)

 Copy code hover
[image]

FileDialog.Title Property (Office)
See also Send feedback

Published: July 09, 2012

Sets or gets the title of a file dialog box displayed using the FileDialog object. Read/write.

Syntax

expression .Title

expression Required. A variable that represents a FileDialog object.

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog Methods (Office)

 Copy code hover
[image]

FileDialog Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Execute | Carries out a user's action right after the Show method is invoked.
Show | Displays a file dialog box and returns a Long indicating whether the user pressed the Action button (-1) or the Cancel button (0). When you call the Show method, no more code executes until the user dismisses the file dialog box. In the case of Open and SaveAs dialog boxes, use the Execute method right after the Show method to carry out the user's action.


FileDialog.Execute Method (Office)

 Copy code hover
[image]

FileDialog.Execute Method (Office)
See also Send feedback

Published: July 09, 2012

Carries out a user's action right after the Show method is invoked.

Syntax

expression .Execute

expression Required. A variable that represents a FileDialog object.

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialog.Show Method (Office)

 Copy code hover
[image]

FileDialog.Show Method (Office)
See also Send feedback

Published: July 09, 2012

Displays a file dialog box and returns a Long indicating whether the user pressed the Action button (-1) or the Cancel button (0). When you call the Show method, no more code executes until the user dismisses the file dialog box. In the case of Open and SaveAs dialog boxes, use the Execute method right after the Show method to carry out the user's action.

Syntax

expression .Show

expression Required. A variable that represents a FileDialog object.

Example

The following example displays a File Picker dialog box using the FileDialog object and displays each selected file in a message box.

VBA Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialog object.
 Dim fd As FileDialog

 'Create a FileDialog object as a File Picker dialog box.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,
 'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant

 'Use a With...End With block to reference the FileDialog object.
 With fd

 'Use the Show method to display the File Picker dialog box and return the user's action.
 'The user pressed the button.
 If .Show = -1 Then

 'Step through each string in the FileDialogSelectedItems collection.
 For Each vrtSelectedItem In .SelectedItems

 'vrtSelectedItem is a string that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message box.
 MsgBox "The path is: " & vrtSelectedItem

 Next vrtSelectedItem
 'The user pressed Cancel.
 Else
 End If
 End With

 'Set the object variable to nothing.
 Set fd = Nothing

End Sub

See also

Concepts

FileDialog Object

Other resources

FileDialog Object Members


FileDialogFilter Object (Office)

 Copy code hover
[image]

FileDialogFilter Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a file filter in a file dialog box displayed through the FileDialog object. Each file filter determines which files are displayed in the file dialog box.

Remarks

Use the Item method with the FileDialogFilters collection to return a FileDialogFilter object. Use the Add method to add a FileDialogFilter object to the FileDialogFilters collection. You can return the extensions that a FileDialogFilter object uses to filter files with the Extensions property and you can return the description of the filter with the Description property; however, both of these properties are read-only. If you want to set the extension or description you must use the Add method.

Example

The following example iterates through the default filters of the SaveAs dialog box and displays the description of each filter that includes a Microsoft Excel file.

Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialogFilters collection.
 Dim fdfs As FileDialogFilters

 'Declare a variable as a FileDialogFilter object.
 Dim fdf As FileDialogFilter

 'Set the FileDialogFilters collection variable to
 'the FileDialogFilters collection of the SaveAs dialog box.
 Set fdfs = Application.FileDialog(msoFileDialogSaveAs).Filters

 'Iterate through the description and extensions of each
 'default filter in the SaveAs dialog box.
 For Each fdf In fdfs

 'Display the description of filters that include
 'Microsoft Excel files.
 If InStr(1, fdf.Extensions, "xls", vbTextCompare) > 0 Then
 MsgBox "Description of filter: " & fdf.Description
 End If
 Next fdf
End Sub

See also

Concepts

Object Model Reference

Other resources

FileDialogFilter Object Members


FileDialogFilter Members (Office)

 Copy code hover
[image]

FileDialogFilter Members (Office)
Send feedback

Published: July 09, 2012

Represents a file filter in a file dialog box displayed through the FileDialog object. Each file filter determines which files are displayed in the file dialog box.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the FileDialogFilter object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the FileDialogFilter object was created. Read-only.
Description | Gets the description of each Filter object as a String value. The description is the text that is displayed in a file dialog box. Read-only.
Extensions | Gets a value containing the extensions that determine which files are displayed in a file dialog box for each Filter object. Read-only.
Parent | Gets the Parent object for the FileDialogFilter object. Read-only.


FileDialogFilter Properties (Office)

 Copy code hover
[image]

FileDialogFilter Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the FileDialogFilter object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the FileDialogFilter object was created. Read-only.
Description | Gets the description of each Filter object as a String value. The description is the text that is displayed in a file dialog box. Read-only.
Extensions | Gets a value containing the extensions that determine which files are displayed in a file dialog box for each Filter object. Read-only.
Parent | Gets the Parent object for the FileDialogFilter object. Read-only.


FileDialogFilter.Application Property (Office)

 Copy code hover
[image]

FileDialogFilter.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the FileDialogFilter object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a FileDialogFilter object.

Return Value

Object

See also

Concepts

FileDialogFilter Object

Other resources

FileDialogFilter Object Members


FileDialogFilter.Creator Property (Office)

 Copy code hover
[image]

FileDialogFilter.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the FileDialogFilter object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a FileDialogFilter object.

Return Value

Long

See also

Concepts

FileDialogFilter Object

Other resources

FileDialogFilter Object Members


FileDialogFilter.Description Property (Office)

 Copy code hover
[image]

FileDialogFilter.Description Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the description of each Filter object as a String value. The description is the text that is displayed in a file dialog box. Read-only.

Syntax

expression .Description

expression Required. A variable that represents a FileDialogFilter object.

Example

The following example iterates through the default filters of the SaveAs dialog box and displays the description of each filter that includes a Microsoft Excel file. The Extensions property is used to find the appropriate filter objects.

VBA Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialogFilters collection.
 Dim fdfs As FileDialogFilters

 'Declare a variable as a FileDialogFilter object.
 Dim fdf As FileDialogFilter

 'Set the FileDialogFilters collection variable to
 'the FileDialogFilters collection of the SaveAs dialog box.
 Set fdfs = Application.FileDialog(msoFileDialogSaveAs).Filters

 'Iterate through the description and extensions of each
 'default filter in the SaveAs dialog box.
 For Each fdf In fdfs

 'Display the description of filters that include
 'Microsoft Excel files.
 If InStr(1, fdf.Extensions, "xls", vbTextCompare) > 0 Then
 MsgBox "Filter description: " & fdf.Description
 End If
 Next fdf

End Sub

See also

Concepts

FileDialogFilter Object

Other resources

FileDialogFilter Object Members


FileDialogFilter.Extensions Property (Office)

 Copy code hover
[image]

FileDialogFilter.Extensions Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value containing the extensions that determine which files are displayed in a file dialog box for each Filter object. Read-only.

Syntax

expression .Extensions

expression An expression that returns a FileDialogFilter object.

Return Value

String

Example

The following example displays the extensions and descriptions for Microsoft Excel files by iterating through the filter in the SaveAs dialog box.

VBA Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialogFilters collection.
 Dim fdfs As FileDialogFilters

 'Declare a variable as a FileDialogFilter object.
 Dim fdf As FileDialogFilter

 'Set the FileDialogFilters collection variable to
 'the FileDialogFilters collection of the SaveAs dialog box.
 Set fdfs = Application.FileDialog(msoFileDialogSaveAs).Filters

 'Iterate through the description and extensions of each
 'default filter in the SaveAs dialog box.
 For Each fdf In fdfs

 'Display the description of filters that include
 'Microsoft Excel files.
 If InStr(1, fdf.Extensions, "xls", vbTextCompare) > 0 Then
 MsgBox "Description of filter: " & fdf.Description
 End If
 Next fdf
End Sub

See also

Concepts

FileDialogFilter Object

Other resources

FileDialogFilter Object Members


FileDialogFilter.Parent Property (Office)

 Copy code hover
[image]

FileDialogFilter.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the FileDialogFilter object. Read-only.

Syntax

expression .Parent

expression A variable that represents a FileDialogFilter object.

Return Value

Object

See also

Concepts

FileDialogFilter Object

Other resources

FileDialogFilter Object Members


FileDialogFilters Object (Office)

 Copy code hover
[image]

FileDialogFilters Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of FileDialogFilter objects that represent the types of files that can be selected in a file dialog box that is displayed using the FileDialog object.

Example

Use the Filters property of the FileDialog object to return a FileDialogFilters collection. The following code returns the FileDialogFilters collection for the File Open dialog box.

VBA Copy code Copy code
Application.FileDialog(msoFileDialogOpen).Filters

Use the Add method to add FileDialogFilter objects to the FileDialogFilters collection. The following example uses the Clear method to clear the collection and then adds filters to the collection. The Clear method completely empties the collection; however, if you do not add any filters to the collection after you clear it, the "All files (*.*)" filter is added automatically.

Copy code Copy code
Sub Main()

    'Declare a variable as a FileDialog object.
    Dim fd As FileDialog

    'Create a FileDialog object as a File Picker dialog box.
    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    'Declare a variable to contain the path
    'of each selected item. Even though the path is aString,
    'the variable must be a Variant because For Each...Next
    'routines only work with Variants and Objects.
    Dim vrtSelectedItem As Variant

    'Use a With...End With block to reference the FileDialog object.
    With fd

        'Change the contents of the Files of Type list.
        'Empty the list by clearing the FileDialogFilters collection.
        .Filters.Clear

        'Add a filter that includes all files.
        .Filters.Add "All files", "*.*"

        'Add a filter that includes GIF and JPEG images and make it the first item in the list.
        .Filters.Add "Images", "*.gif; *.jpg; *.jpeg", 1

        'Use the Show method to display the File Picker dialog box and return the user's action.
        'The user pressed the button.
        If .Show = -1 Then

            'Step through eachString in the FileDialogSelectedItems collection.
            For Each vrtSelectedItem In .SelectedItems

                'vrtSelectedItem is aString that contains the path of each selected item.
                'You can use any file I/O functions that you want to work with this path.
                'This example displays the path in a message box.
                MsgBox "Path name: " & vrtSelectedItem

            Next vrtSelectedItem
        'The user pressed Cancel.
        Else
        End If
    End With

    'Set the object variable to Nothing.
    Set fd = Nothing

End Sub

When changing the FileDialogFilters collection, remember that each application can only create an instance of a single FileDialog object. This means that the FileDialogFilters collection resets to its default filters whenever you call the FileDialog method with a new dialog box type. The following example iterates through the default filters of the SaveAs dialog box and displays the description of each filter that includes a Microsoft Excel file.

Copy code Copy code
Sub Main()

    'Declare a variable as a FileDialogFilters collection.
    Dim fdfs As FileDialogFilters

    'Declare a variable as a FileDialogFilter object.
    Dim fdf As FileDialogFilter

    'Set the FileDialogFilters collection variable to
    'the FileDialogFilters collection of the SaveAs dialog box.
    Set fdfs = Application.FileDialog(msoFileDialogSaveAs).Filters

    'Iterate through the description and extensions of each
    'default filter in the SaveAs dialog box.
    For Each fdf In fdfs

        'Display the description of filters that include
        'Microsoft Excel files
        If InStr(1, fdf.Extensions, "xls", vbTextCompare) > 0 Then
            MsgBox "Description of filter: " & fdf.Description
        End If
    Next fdf

End Sub
Note Note

A run-time error will occur if the Filters property is used in conjunction with the Clear, Add, or Delete methods when applied to a Save As FileDiaog object. For example, Application.FileDialog(msoFileDialogSaveAs).Filters.Clear will result in a run-time error.

See also

Concepts

Object Model Reference

Other resources

FileDialogFilters Object Members


FileDialogFilters Members (Office)

 Copy code hover
[image]

FileDialogFilters Members (Office)
Send feedback

Published: July 09, 2012

A collection of FileDialogFilter objects that represent the types of files that can be selected in a file dialog box that is displayed using the FileDialog object.

Methods

Name | Description
Add | Adds a new file filter to the list of filters in the Files of type drop-down list box in the File dialog box. Returns a FileDialogFilter object that represents the newly added file filter.
Clear | Removes all filters currently applied in a file dialog box.
Delete | Removes a file dialog filter.
Item | Gets a FileDialogFilter object that is a member of the specified FileDialogFilters collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the FileDialogFilters object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the FileDialogFilters collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the FileDialogFilters object was created. Read-only.
Parent | Gets the Parent object for the FileDialogFilters object. Read-only.


FileDialogFilters Properties (Office)

 Copy code hover
[image]

FileDialogFilters Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the FileDialogFilters object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the FileDialogFilters collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the FileDialogFilters object was created. Read-only.
Parent | Gets the Parent object for the FileDialogFilters object. Read-only.


FileDialogFilters.Application Property (Office)

 Copy code hover
[image]

FileDialogFilters.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the FileDialogFilters object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a FileDialogFilters object.

Return Value

Object

See also

Concepts

FileDialogFilters Object

Other resources

FileDialogFilters Object Members


FileDialogFilters.Count Property (Office)

 Copy code hover
[image]

FileDialogFilters.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the FileDialogFilters collection. Read-only.

Syntax

expression .Count

expression A variable that represents a FileDialogFilters object.

Return Value

Long

See also

Concepts

FileDialogFilters Object

Other resources

FileDialogFilters Object Members


FileDialogFilters.Creator Property (Office)

 Copy code hover
[image]

FileDialogFilters.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the FileDialogFilters object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a FileDialogFilters object.

Return Value

Long

See also

Concepts

FileDialogFilters Object

Other resources

FileDialogFilters Object Members


FileDialogFilters.Parent Property (Office)

 Copy code hover
[image]

FileDialogFilters.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the FileDialogFilters object. Read-only.

Syntax

expression .Parent

expression A variable that represents a FileDialogFilters object.

Return Value

Object

See also

Concepts

FileDialogFilters Object

Other resources

FileDialogFilters Object Members


FileDialogFilters Methods (Office)

 Copy code hover
[image]

FileDialogFilters Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a new file filter to the list of filters in the Files of type drop-down list box in the File dialog box. Returns a FileDialogFilter object that represents the newly added file filter.
Clear | Removes all filters currently applied in a file dialog box.
Delete | Removes a file dialog filter.
Item | Gets a FileDialogFilter object that is a member of the specified FileDialogFilters collection.


FileDialogFilters.Add Method (Office)

 Copy code hover
[image]

FileDialogFilters.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a new file filter to the list of filters in the Files of type drop-down list box in the File dialog box. Returns a FileDialogFilter object that represents the newly added file filter.

Syntax

expression .Add(Description, Extensions, Position)

expression Required. A variable that represents a FileDialogFilters object.

Parameters

Name

Required/Optional

Data Type

Description

Description

Required

String

The text representing the description of the file name extension you want to add to the list of filters.

Extensions

Required

String

The text representing the file name extension you want to add to the list of filters. More than one extension may be specified and each must be separated by a semi-colon. For example, the argument can be assigned to the string: "*.txt; *.htm".

Note Note

Parentheses do not need to be added around the extensions. Microsoft Office will automatically add parentheses around the extensions string when the description and extensions strings are concatenated into one file filter item.

Position

Optional

Variant

A number that indicates the position of the new control in the filter list. The new filter will be inserted before the filter at this position. If this argument is omitted, the filter is added at the end of the list.

Remarks

Each filter in a list is made up of two parts: the file name extension (that is, .txt) and the text description of the file name extension (that is, Text Files). Together, the file filter would appear in the Files of type drop down list box as: Text Files (*.txt). Note that when a filter is added to the list, the default filters are not removed. Filters are only displayed when the Windows option is checked. If Position is invalid, an out of range runtime error is displayed. If the Description and Extensions value are invalid, a runtime error (parse) is displayed.

See also

Concepts

FileDialogFilters Object

Other resources

FileDialogFilters Object Members


FileDialogFilters.Clear Method (Office)

 Copy code hover
[image]

FileDialogFilters.Clear Method (Office)
See also Send feedback

Published: July 09, 2012

Removes all filters currently applied in a file dialog box.

Syntax

expression .Clear

expression A variable that represents a FileDialogFilters object.

Example

The following example iterates through the default filters of the SaveAs dialog box and displays the description of each filter that includes a Microsoft Excel file.

VBA Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialogFilters collection.
 Dim fdfs As FileDialogFilters

 'Declare a variable as a FileDialogFilter object.
 Dim fdf As FileDialogFilter

 'Set the FileDialogFilters collection variable to
 'the FileDialogFilters collection of the SaveAs dialog box.
 Set fdfs = Application.FileDialog(msoFileDialogSaveAs).Filters

 'Iterate through the description and extensions of each
 'default filter in the SaveAs dialog box.
 For Each fdf In fdfs

 'Display the description of filters that include
 'Microsoft Excel files
 If InStr(1, fdf.Extensions, "xls", vbTextCompare) > 0 Then
 MsgBox "Description of filter: " & fdf.Description
 End If
 Next fdf

End Sub

See also

Concepts

FileDialogFilters Object

Other resources

FileDialogFilters Object Members


FileDialogFilters.Delete Method (Office)

 Copy code hover
[image]

FileDialogFilters.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Removes a file dialog filter.

Syntax

expression .Delete(filter)

expression Required. A variable that represents a FileDialogFilters object.

Parameters

Name | Required/Optional | Data Type | Description
filter | Optional | Variant | The filter to be removed.

See also

Concepts

FileDialogFilters Object

Other resources

FileDialogFilters Object Members


FileDialogFilters.Item Method (Office)

 Copy code hover
[image]

FileDialogFilters.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Gets a FileDialogFilter object that is a member of the specified FileDialogFilters collection.

Syntax

expression .Item(Index)

expression Required. A variable that represents a FileDialogFilters object.

See also

Concepts

FileDialogFilters Object

Other resources

FileDialogFilters Object Members


FileDialogSelectedItems Object (Office)

 Copy code hover
[image]

FileDialogSelectedItems Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of String values that correspond to the paths of the files or folders that a user has selected from a file dialog box displayed through the FileDialog object.

Example

Use the SelectedItems property with the FileDialog object to return a FileDialogSelectedItems collection. The following example displays a File Picker dialog box and displays each selected file in a message box.

Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialog object.
 Dim fd As FileDialog

 'Create a FileDialog object as a File Picker dialog box.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,
 'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant

 'Use a With...End With block to reference the FileDialog object.
 With fd

 'Allow the selection of multiple file.
 .AllowMultiSelect = True

 'Use the Show method to display the File Picker dialog box and return the user's action.
 'The user pressed the button.
 If .Show = -1 Then

 'Step through each string in the FileDialogSelectedItems collection
 For Each vrtSelectedItem In .SelectedItems

 'vrtSelectedItem is aString that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message box.
 MsgBox "Selected item's path: " & vrtSelectedItem

 Next vrtSelectedItem
 'The user pressed Cancel.
 Else
 End If
 End With

 'Set the object variable to Nothing.
 Set fd = Nothing

End Sub

See also

Concepts

Object Model Reference

Other resources

FileDialogSelectedItems Object Members


FileDialogSelectedItems Members (Office)

 Copy code hover
[image]

FileDialogSelectedItems Members (Office)
Send feedback

Published: July 09, 2012

A collection of String values that correspond to the paths of the files or folders that a user has selected from a file dialog box displayed through the FileDialog object.

Methods

Name | Description
Item | Gets a String that corresponds to the path of one of the files that the user selected from a file dialog box that was displayed using the Show method of the FileDialog object.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the FileDialogSelectedItems object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the FileDialogSelectedItems collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the FileDialogSelectedItems object was created. Read-only.
Parent | Gets the Parent object for the FileDialogSelectedItems object. Read-only.


FileDialogSelectedItems Properties (Office)

 Copy code hover
[image]

FileDialogSelectedItems Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the FileDialogSelectedItems object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the FileDialogSelectedItems collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the FileDialogSelectedItems object was created. Read-only.
Parent | Gets the Parent object for the FileDialogSelectedItems object. Read-only.


FileDialogSelectedItems.Application Property (Office)

 Copy code hover
[image]

FileDialogSelectedItems.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the FileDialogSelectedItems object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a FileDialogSelectedItems object.

Return Value

Object

See also

Concepts

FileDialogSelectedItems Object

Other resources

FileDialogSelectedItems Object Members


FileDialogSelectedItems.Count Property (Office)

 Copy code hover
[image]

FileDialogSelectedItems.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the FileDialogSelectedItems collection. Read-only.

Syntax

expression .Count

expression A variable that represents a FileDialogSelectedItems object.

Return Value

Long

Example

The following example displays a File Picker dialog box and displays each selected file in a message box.

VBA Copy code Copy code
Sub Main()

 'Declare a variable as a FileDialog object.
 Dim fd As FileDialog
 Dim cnt As Integer

 'Create a FileDialog object as a File Picker dialog box.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,
 'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant

 'Use a With...End With block to reference the FileDialog object.
 With fd

 'Allow the selection of multiple file.
 .AllowMultiSelect = True

 'Use the Show method to display the File Picker dialog box and return the user's action.
 'The user pressed the button.
 If .Show = -1 Then

 'Step through each string in the FileDialogSelectedItems collection
 For cnt = 0 To .SelectedItems.Count - 1

 'vrtSelectedItem is aString that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message box.
 MsgBox "Selected item's path: " & vrtSelectedItem(cnt)

 Next
 'The user pressed Cancel.
 Else
 End If
 End With

 'Set the object variable to Nothing.
 Set fd = Nothing

End Sub

See also

Concepts

FileDialogSelectedItems Object

Other resources

FileDialogSelectedItems Object Members


FileDialogSelectedItems.Creator Property (Office)

 Copy code hover
[image]

FileDialogSelectedItems.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the FileDialogSelectedItems object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a FileDialogSelectedItems object.

Return Value

Long

See also

Concepts

FileDialogSelectedItems Object

Other resources

FileDialogSelectedItems Object Members


FileDialogSelectedItems.Parent Property (Office)

 Copy code hover
[image]

FileDialogSelectedItems.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the FileDialogSelectedItems object. Read-only.

Syntax

expression .Parent

expression A variable that represents a FileDialogSelectedItems object.

Return Value

Object

See also

Concepts

FileDialogSelectedItems Object

Other resources

FileDialogSelectedItems Object Members


FileDialogSelectedItems Methods (Office)

 Copy code hover
[image]

FileDialogSelectedItems Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Item | Gets a String that corresponds to the path of one of the files that the user selected from a file dialog box that was displayed using the Show method of the FileDialog object.


FileDialogSelectedItems.Item Method (Office)

 Copy code hover
[image]

FileDialogSelectedItems.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Gets a String that corresponds to the path of one of the files that the user selected from a file dialog box that was displayed using the Show method of the FileDialog object.

Syntax

expression .Item(Index)

expression Required. A variable that represents a FileDialogSelectedItems object.

See also

Concepts

FileDialogSelectedItems Object

Other resources

FileDialogSelectedItems Object Members


FileTypes Object (Office)

 Copy code hover
[image]

FileTypes Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of values of the type msoFileType that determine which types of files are returned during a search.

Remarks

There is only one FileTypes collection for all searches so it's important to clear the FileTypes collection before executing a search unless you wish to search for file types from previous searches. The easiest way to clear the collection is to set the FileType property to the first file type for which you want to search. You can also remove individual types using the Remove method. To determine the file type of each item in the collection, use the Item method to return the msoFileType value.

See also

Concepts

Object Model Reference

Other resources

FileTypes Object Members


FileTypes Members (Office)

 Copy code hover
[image]

FileTypes Members (Office)
Send feedback

Published: July 09, 2012

A collection of values of the type msoFileType that determine which types of files are returned during a search.

Methods

Name | Description
Add | Adds a new file type to a file search.
Remove | Removes a FileType object from the collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the FileTypes object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the FileTypes collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the FileTypes object was created. Read-only.
Item | Gets a value that indicates which file type will be searched for. Read-only.


FileTypes Properties (Office)

 Copy code hover
[image]

FileTypes Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the FileTypes object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the FileTypes collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the FileTypes object was created. Read-only.
Item | Gets a value that indicates which file type will be searched for. Read-only.


FileTypes.Application Property (Office)

 Copy code hover
[image]

FileTypes.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the FileTypes object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a FileTypes object.

Return Value

Object

See also

Concepts

FileTypes Object

Other resources

FileTypes Object Members


FileTypes.Count Property (Office)

 Copy code hover
[image]

FileTypes.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the FileTypes collection. Read-only.

Syntax

expression .Count

expression A variable that represents a FileTypes object.

Return Value

Long

See also

Concepts

FileTypes Object

Other resources

FileTypes Object Members


FileTypes.Creator Property (Office)

 Copy code hover
[image]

FileTypes.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the FileTypes object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a FileTypes object.

Return Value

Long

See also

Concepts

FileTypes Object

Other resources

FileTypes Object Members


FileTypes.Item Property (Office)

 Copy code hover
[image]

FileTypes.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value that indicates which file type will be searched for. Read-only.

Syntax

expression .Item(Index)

expression Required. A variable that represents a FileTypes object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | The index number of the object to be returned.

See also

Concepts

FileTypes Object

Other resources

FileTypes Object Members


FileTypes Methods (Office)

 Copy code hover
[image]

FileTypes Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a new file type to a file search.
Remove | Removes a FileType object from the collection.


FileTypes.Add Method (Office)

 Copy code hover
[image]

FileTypes.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a new file type to a file search.

Syntax

expression .Add(FileType)

expression Required. A variable that represents a FileTypes object.

Parameters

Name | Required/Optional | Data Type | Description
FileType | Required | MsoFileType | Specifies the type of file for which to search.

See also

Concepts

FileTypes Object

Other resources

FileTypes Object Members


FileTypes.Remove Method (Office)

 Copy code hover
[image]

FileTypes.Remove Method (Office)
See also Send feedback

Published: July 09, 2012

Removes a FileType object from the collection.

Syntax

expression .Remove(Index)

expression Required. A variable that represents a FileTypes object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | The index number of the file type to be removed.

See also

Concepts

FileTypes Object

Other resources

FileTypes Object Members


Font2 Object (Office)

 Copy code hover
[image]

Font2 Object (Office)
See also Send feedback

Published: July 09, 2012

Contains font attributes (for example, font name, font size, and color) for an object.

Example

The following example changes the formatting of the Heading 2 style in the active document to Arial and bold.

VBA Copy code Copy code
With ActiveDocument.Styles(wdStyleHeading2).Font2
 .Name = "Arial"
 .Italic = True
End With

See also

Concepts

Object Model Reference

Other resources

Font2 Object Members


Font2 Members (Office)

 Copy code hover
[image]

Font2 Members (Office)
Send feedback

Published: July 09, 2012

Contains font attributes (for example, font name, font size, and color) for an object.

Properties

Name | Description
Allcaps | True if the font is formatted as all capital letters. Read/write.
Application | Gets an object that represents the application the Font2 object is used in. Read-only.
AutorotateNumbers | Gets or sets a value that specifies whether the numbers in a numbered list should be rotated when the text is rotated. Read/write.
BaselineOffset | Gets or sets a value specifying the horizontaol offset of the selected font. Read/write.
Bold | Gets or sets a value specifying whether the font should be bold. Read/write.
Caps | Gets or sets a value specifying that the text should be capitalized. Read/write.
Creator | Gets a value indicating the application the object was created in. Read-only.
DoubleStrikeThrough | True if the specified font is formatted as double strikethrough text. Read/write.
Embeddable | Gets a value indicating whether the font can be embedded in a page. Read-only.
Embedded | Gets a value specifying whether the font is embedded in a page. Read-only.
Equalize | Gets or sets a value specifying whether the text for a selection should be spaced equal distances apart. Read/write.
Fill | Gets the formatting properties for the font of the specified text. Read-only
Glow | Gets a value indicating whether the font is displayed as a glow effect. Read-only.
Highlight | Gets a value indicating whether the font is displayed as highlighted. Read-only.
Italic | Gets or sets a value specifying whether the text for a selection is italic. Read/write.
Kerning | Gets or sets a value specifying the amount of spacing between text characters. Read/write.
Line | Gets a value specifiying the format of a line. Read-only.
Name | Gets or sets a value specifying the font to use for a selection. Read/write.
NameAscii | Gets or sets the font used for Latin text (characters with character codes from 0 (zero) through 127). Read/write.
NameComplexScript | Gets or sets the complex script font name. Used for mixed language text. Read/write.
NameFarEast | Gets or sets an East Asian font name. Read/write.
NameOther | Gets or sets the font used for characters whose character set numbers are greater than 127. Read/write.
Parent | Gets the parent of the Font2 object. Read-only.
Reflection | Gets a value specifying the type of reflection format for the selection of text. Read-only.
Shadow | Gets the value specifying the type of shadow effect for the selection of text. Read-only.
Size | Gets or sets a value specifying the size of the font. Read/write.
Smallcaps | Gets or sets a value specifying whether small caps should be used with the slection of text. Small caps are the same height as the lowercase letters in a slection of text. Read/write.
SoftEdgeFormat | Gets or sets a value specifying the type of soft edge effect used in a selection of text. Read/write.
Spacing | Gets or sets a value specifying the spacing between characters in a selection of text. Read/write.
Strike | Gets or sets a value specifying the strike format used for a selection of text. Read/write.
StrikeThrough | Gets or sets a value specifying the text should be rendered in a strikethrough appearance. Read/write.
Subscript | Gets or sets a value specifying that the selected text should be displayed as subscript. Read/write.
Superscript | Gets or sets a value specifying that the selected text should be displayed as superscript. Read/write.
UnderlineColor | Gets a value specifying the color of the underline for the selected text. Read-only.
UnderlineStyle | Gets or sets a value specifying the underline style for the selected text. Read/write.
WordArtformat | Gets or sets a value specifying the text effect for the selected text. Read/write.


Font2 Properties (Office)

 Copy code hover
[image]

Font2 Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Allcaps | True if the font is formatted as all capital letters. Read/write.
Application | Gets an object that represents the application the Font2 object is used in. Read-only.
AutorotateNumbers | Gets or sets a value that specifies whether the numbers in a numbered list should be rotated when the text is rotated. Read/write.
BaselineOffset | Gets or sets a value specifying the horizontaol offset of the selected font. Read/write.
Bold | Gets or sets a value specifying whether the font should be bold. Read/write.
Caps | Gets or sets a value specifying that the text should be capitalized. Read/write.
Creator | Gets a value indicating the application the object was created in. Read-only.
DoubleStrikeThrough | True if the specified font is formatted as double strikethrough text. Read/write.
Embeddable | Gets a value indicating whether the font can be embedded in a page. Read-only.
Embedded | Gets a value specifying whether the font is embedded in a page. Read-only.
Equalize | Gets or sets a value specifying whether the text for a selection should be spaced equal distances apart. Read/write.
Fill | Gets the formatting properties for the font of the specified text. Read-only
Glow | Gets a value indicating whether the font is displayed as a glow effect. Read-only.
Highlight | Gets a value indicating whether the font is displayed as highlighted. Read-only.
Italic | Gets or sets a value specifying whether the text for a selection is italic. Read/write.
Kerning | Gets or sets a value specifying the amount of spacing between text characters. Read/write.
Line | Gets a value specifiying the format of a line. Read-only.
Name | Gets or sets a value specifying the font to use for a selection. Read/write.
NameAscii | Gets or sets the font used for Latin text (characters with character codes from 0 (zero) through 127). Read/write.
NameComplexScript | Gets or sets the complex script font name. Used for mixed language text. Read/write.
NameFarEast | Gets or sets an East Asian font name. Read/write.
NameOther | Gets or sets the font used for characters whose character set numbers are greater than 127. Read/write.
Parent | Gets the parent of the Font2 object. Read-only.
Reflection | Gets a value specifying the type of reflection format for the selection of text. Read-only.
Shadow | Gets the value specifying the type of shadow effect for the selection of text. Read-only.
Size | Gets or sets a value specifying the size of the font. Read/write.
Smallcaps | Gets or sets a value specifying whether small caps should be used with the slection of text. Small caps are the same height as the lowercase letters in a slection of text. Read/write.
SoftEdgeFormat | Gets or sets a value specifying the type of soft edge effect used in a selection of text. Read/write.
Spacing | Gets or sets a value specifying the spacing between characters in a selection of text. Read/write.
Strike | Gets or sets a value specifying the strike format used for a selection of text. Read/write.
StrikeThrough | Gets or sets a value specifying the text should be rendered in a strikethrough appearance. Read/write.
Subscript | Gets or sets a value specifying that the selected text should be displayed as subscript. Read/write.
Superscript | Gets or sets a value specifying that the selected text should be displayed as superscript. Read/write.
UnderlineColor | Gets a value specifying the color of the underline for the selected text. Read-only.
UnderlineStyle | Gets or sets a value specifying the underline style for the selected text. Read/write.
WordArtformat | Gets or sets a value specifying the text effect for the selected text. Read/write.


Font2.Allcaps Property (Office)

 Copy code hover
[image]

Font2.Allcaps Property (Office)
See also Send feedback

Published: July 09, 2012

True if the font is formatted as all capital letters. Read/write.

Syntax

expression .Allcaps

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Application Property (Office)

 Copy code hover
[image]

Font2.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an object that represents the application the Font2 object is used in. Read-only.

Syntax

expression .Application

expression An expression that returns a Font2 object.

Return Value

Object

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.AutorotateNumbers Property (Office)

 Copy code hover
[image]

Font2.AutorotateNumbers Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value that specifies whether the numbers in a numbered list should be rotated when the text is rotated. Read/write.

Syntax

expression .AutorotateNumbers

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.BaselineOffset Property (Office)

 Copy code hover
[image]

Font2.BaselineOffset Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying the horizontaol offset of the selected font. Read/write.

Syntax

expression .BaselineOffset

expression An expression that returns a Font2 object.

Return Value

Single

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Bold Property (Office)

 Copy code hover
[image]

Font2.Bold Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying whether the font should be bold. Read/write.

Syntax

expression .Bold

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Caps Property (Office)

 Copy code hover
[image]

Font2.Caps Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying that the text should be capitalized. Read/write.

Syntax

expression .Caps

expression An expression that returns a Font2 object.

Return Value

MsoTextCaps

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Creator Property (Office)

 Copy code hover
[image]

Font2.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value indicating the application the object was created in. Read-only.

Syntax

expression .Creator

expression An expression that returns a Font2 object.

Return Value

Long

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.DoubleStrikeThrough Property (Office)

 Copy code hover
[image]

Font2.DoubleStrikeThrough Property (Office)
See also Send feedback

Published: July 09, 2012

True if the specified font is formatted as double strikethrough text. Read/write.

Syntax

expression .DoubleStrikeThrough

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Embeddable Property (Office)

 Copy code hover
[image]

Font2.Embeddable Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value indicating whether the font can be embedded in a page. Read-only.

Syntax

expression .Embeddable

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Embedded Property (Office)

 Copy code hover
[image]

Font2.Embedded Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value specifying whether the font is embedded in a page. Read-only.

Syntax

expression .Embedded

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Equalize Property (Office)

 Copy code hover
[image]

Font2.Equalize Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying whether the text for a selection should be spaced equal distances apart. Read/write.

Syntax

expression .Equalize

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Fill Property (Office)

 Copy code hover
[image]

Font2.Fill Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the formatting properties for the font of the specified text. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Fill

expression An expression that returns a Font2 object.

Example

The following code assumes that a shape has been inserted into sheet1. The code inserts text into the shape and changes the fore color of the font to bold and red. It then adds a carriage return after the second word creating a second paragraph and aligns the paragraph to the right.

VBA Copy code Copy code
Sub TestShapeAttributes()
 Dim shp As Excel.Shape
 Dim rng As Office.TextRange2
 Dim rngWord As Office.TextRange2
 Dim rngRun As Office.TextRange2
 Dim rngPara As Office.TextRange2
 Dim fnt As Office.Font2

 Set shp = ActiveSheet.Shapes(1)
 Set rng = shp.TextFrame2.TextRange
 rng.Text = "This is test text."

 Set rngWord = rng.Words(2)
 Set fnt = rngWord.Font
 With fnt
 .Fill.ForeColor.RGB = RGB(255, 0, 0)
 .Bold = msoTrue
 End With

 Set rngRun = rng.Runs(3)
 rngRun.InsertBefore vbCr

 Set rngPara = rng.Paragraphs(2)
 rngPara.ParagraphFormat.Alignment = msoAlignRight
End Sub

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Glow Property (Office)

 Copy code hover
[image]

Font2.Glow Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value indicating whether the font is displayed as a glow effect. Read-only.

Syntax

expression .Glow

expression An expression that returns a Font2 object.

Return Value

GlowFormat

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Highlight Property (Office)

 Copy code hover
[image]

Font2.Highlight Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value indicating whether the font is displayed as highlighted. Read-only.

Syntax

expression .Highlight

expression An expression that returns a Font2 object.

Return Value

ColorFormat

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Italic Property (Office)

 Copy code hover
[image]

Font2.Italic Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying whether the text for a selection is italic. Read/write.

Syntax

expression .Italic

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Kerning Property (Office)

 Copy code hover
[image]

Font2.Kerning Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying the amount of spacing between text characters. Read/write.

Syntax

expression .Kerning

expression An expression that returns a Font2 object.

Return Value

Single

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Line Property (Office)

 Copy code hover
[image]

Font2.Line Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value specifiying the format of a line. Read-only.

Syntax

expression .Line

expression An expression that returns a Font2 object.

Return Value

LineFormat

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Name Property (Office)

 Copy code hover
[image]

Font2.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying the font to use for a selection. Read/write.

Syntax

expression .Name

expression An expression that returns a Font2 object.

Return Value

String

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.NameAscii Property (Office)

 Copy code hover
[image]

Font2.NameAscii Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the font used for Latin text (characters with character codes from 0 (zero) through 127). Read/write.

Syntax

expression .NameAscii

expression An expression that returns a Font2 object.

Return Value

String

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.NameComplexScript Property (Office)

 Copy code hover
[image]

Font2.NameComplexScript Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the complex script font name. Used for mixed language text. Read/write.

Syntax

expression .NameComplexScript

expression An expression that returns a Font2 object.

Return Value

String

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.NameFarEast Property (Office)

 Copy code hover
[image]

Font2.NameFarEast Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets an East Asian font name. Read/write.

Syntax

expression .NameFarEast

expression An expression that returns a Font2 object.

Return Value

String

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.NameOther Property (Office)

 Copy code hover
[image]

Font2.NameOther Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the font used for characters whose character set numbers are greater than 127. Read/write.

Syntax

expression .NameOther

expression An expression that returns a Font2 object.

Return Value

String

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Parent Property (Office)

 Copy code hover
[image]

Font2.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the parent of the Font2 object. Read-only.

Syntax

expression .Parent

expression An expression that returns a Font2 object.

Return Value

Object

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Reflection Property (Office)

 Copy code hover
[image]

Font2.Reflection Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value specifying the type of reflection format for the selection of text. Read-only.

Syntax

expression .Reflection

expression An expression that returns a Font2 object.

Return Value

ReflectionFormat

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Shadow Property (Office)

 Copy code hover
[image]

Font2.Shadow Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the value specifying the type of shadow effect for the selection of text. Read-only.

Syntax

expression .Shadow

expression An expression that returns a Font2 object.

Return Value

ShadowFormat

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Size Property (Office)

 Copy code hover
[image]

Font2.Size Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying the size of the font. Read/write.

Syntax

expression .Size

expression An expression that returns a Font2 object.

Return Value

Single

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Smallcaps Property (Office)

 Copy code hover
[image]

Font2.Smallcaps Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying whether small caps should be used with the slection of text. Small caps are the same height as the lowercase letters in a slection of text. Read/write.

Syntax

expression .Smallcaps

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.SoftEdgeFormat Property (Office)

 Copy code hover
[image]

Font2.SoftEdgeFormat Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying the type of soft edge effect used in a selection of text. Read/write.

Syntax

expression .SoftEdgeFormat

expression An expression that returns a Font2 object.

Return Value

MsoSoftEdgeType

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Spacing Property (Office)

 Copy code hover
[image]

Font2.Spacing Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying the spacing between characters in a selection of text. Read/write.

Syntax

expression .Spacing

expression An expression that returns a Font2 object.

Return Value

Single

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Strike Property (Office)

 Copy code hover
[image]

Font2.Strike Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying the strike format used for a selection of text. Read/write.

Syntax

expression .Strike

expression An expression that returns a Font2 object.

Return Value

MsoTextStrike

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.StrikeThrough Property (Office)

 Copy code hover
[image]

Font2.StrikeThrough Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying the text should be rendered in a strikethrough appearance. Read/write.

Syntax

expression .StrikeThrough

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Subscript Property (Office)

 Copy code hover
[image]

Font2.Subscript Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying that the selected text should be displayed as subscript. Read/write.

Syntax

expression .Subscript

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.Superscript Property (Office)

 Copy code hover
[image]

Font2.Superscript Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying that the selected text should be displayed as superscript. Read/write.

Syntax

expression .Superscript

expression An expression that returns a Font2 object.

Return Value

MsoTriState

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.UnderlineColor Property (Office)

 Copy code hover
[image]

Font2.UnderlineColor Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value specifying the color of the underline for the selected text. Read-only.

Syntax

expression .UnderlineColor

expression An expression that returns a Font2 object.

Return Value

ColorFormat

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.UnderlineStyle Property (Office)

 Copy code hover
[image]

Font2.UnderlineStyle Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying the underline style for the selected text. Read/write.

Syntax

expression .UnderlineStyle

expression An expression that returns a Font2 object.

Return Value

MsoTextUnderlineType

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


Font2.WordArtformat Property (Office)

 Copy code hover
[image]

Font2.WordArtformat Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying the text effect for the selected text. Read/write.

Syntax

expression .WordArtformat

expression An expression that returns a Font2 object.

Return Value

MsoPresetTextEffect

See also

Concepts

Font2 Object

Other resources

Font2 Object Members


GlowFormat Object (Office)

 Copy code hover
[image]

GlowFormat Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a glow effect around an Office graphic.

Example

This example applies glow to the text in the second shape on the second slide in a PowerPoint presentation:

VBA Copy code Copy code
With ActivePresentation.Slides(2).Shapes(2)
 .Text.Font.Glowformat = msoGlowType2
End With

See also

Concepts

Object Model Reference

Other resources

GlowFormat Object Members


GlowFormat Members (Office)

 Copy code hover
[image]

GlowFormat Members (Office)
Send feedback

Published: July 09, 2012

Represents a glow effect around an Office graphic.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the GlowFormat object. Read-only.
Color | Gets a ColorFormat object that represents the color of text formatted as glow. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the GlowFormat object was created. Read-only.
Radius | Gets or sets the radius value of the glow effect for the GlowFormat object. Read/write.
Transparency | Returns or sets the degree of transparency of the specified glow as a value between 0.0 (opaque) and 1.0 (clear). Read/write


GlowFormat Properties (Office)

 Copy code hover
[image]

GlowFormat Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the GlowFormat object. Read-only.
Color | Gets a ColorFormat object that represents the color of text formatted as glow. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the GlowFormat object was created. Read-only.
Radius | Gets or sets the radius value of the glow effect for the GlowFormat object. Read/write.
Transparency | Returns or sets the degree of transparency of the specified glow as a value between 0.0 (opaque) and 1.0 (clear). Read/write


GlowFormat.Application Property (Office)

 Copy code hover
[image]

GlowFormat.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the GlowFormat object. Read-only.

Syntax

expression .Application

expression An expression that returns a GlowFormat object.

Return Value

Object

See also

Concepts

GlowFormat Object

Other resources

GlowFormat Object Members


GlowFormat.Color Property (Office)

 Copy code hover
[image]

GlowFormat.Color Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a ColorFormat object that represents the color of text formatted as glow. Read-only.

Syntax

expression .Color

expression An expression that returns a GlowFormat object.

Return Value

ColorFormat

See also

Concepts

GlowFormat Object

Other resources

GlowFormat Object Members


GlowFormat.Creator Property (Office)

 Copy code hover
[image]

GlowFormat.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the GlowFormat object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a GlowFormat object.

Return Value

Long

See also

Concepts

GlowFormat Object

Other resources

GlowFormat Object Members


GlowFormat.Radius Property (Office)

 Copy code hover
[image]

GlowFormat.Radius Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the radius value of the glow effect for the GlowFormat object. Read/write.

Syntax

expression .Radius

expression An expression that returns a GlowFormat object.

Return Value

Single

See also

Concepts

GlowFormat Object

Other resources

GlowFormat Object Members


GlowFormat.Transparency Property (Office)

 Copy code hover
[image]

GlowFormat.Transparency Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets the degree of transparency of the specified glow as a value between 0.0 (opaque) and 1.0 (clear). Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Transparency

expression An expression that returns a GlowFormat object.

See also

Concepts

GlowFormat Object

Other resources

GlowFormat Object Members


GradientStop Object (Office)

 Copy code hover
[image]

GradientStop Object (Office)
See also Send feedback

Published: July 09, 2012

Represents one gradient stop.

Remarks

Gradients are a smooth transition from one color state to another. The endpoints of these sections are called stops.

Example

The following example adds three gradient color stops and then deletes the first gradient stop.

VBA Copy code Copy code
Sub gradients()
 Set myDocument = ActivePresentation.Slides(1)
 Set GradientShapeFill = myDocument.Shapes.AddShape(msoShapeRectangle, 90, 90, 90, 80).Fill
 With GradientShapeFill
 .ForeColor.RGB = RGB(0, 128, 128)
 .OneColorGradient msoGradientHorizontal, 1, 1
 .GradientStops.Insert RGB(255, 0, 0), 0.25
 .GradientStops.Insert RGB(0, 255, 0), 0.5
 .GradientStops.Insert RGB(0, 0, 255), 0.75
 End With
 GradientShapeFill.GradientStops.Delete (1)
End Sub

See also

Concepts

Object Model Reference

Other resources

GradientStop Object Members


GradientStop Members (Office)

 Copy code hover
[image]

GradientStop Members (Office)
Send feedback

Published: July 09, 2012

Represents one gradient stop.

Properties

Name | Description
Application | When used without an object qualifier, this property returns an Application object that represents the Microsoft Office application. When used with an object qualifier, this property returns an Application object that represents the creator of the specified object. Read-only.
Color | Gets a value representing the color of the gradient stop. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the GradientStop object was created. Read-only.
Position | Gets or sets a value representing the position of a stop within the gradient expressed as a percent. Read/write.
Transparency | Gets or sets a value representing the opacity of the gradient fill expressed as a percent. Read/write.


GradientStop Properties (Office)

 Copy code hover
[image]

GradientStop Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | When used without an object qualifier, this property returns an Application object that represents the Microsoft Office application. When used with an object qualifier, this property returns an Application object that represents the creator of the specified object. Read-only.
Color | Gets a value representing the color of the gradient stop. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the GradientStop object was created. Read-only.
Position | Gets or sets a value representing the position of a stop within the gradient expressed as a percent. Read/write.
Transparency | Gets or sets a value representing the opacity of the gradient fill expressed as a percent. Read/write.


GradientStop.Application Property (Office)

 Copy code hover
[image]

GradientStop.Application Property (Office)
See also Send feedback

Published: July 09, 2012

When used without an object qualifier, this property returns an Application object that represents the Microsoft Office application. When used with an object qualifier, this property returns an Application object that represents the creator of the specified object. Read-only.

Syntax

expression .Application

expression An expression that returns a GradientStop object.

Return Value

Object

Remarks

You can use this property with an OLE Automation object to return the application of that object.

See also

Concepts

GradientStop Object

Other resources

GradientStop Object Members


GradientStop.Color Property (Office)

 Copy code hover
[image]

GradientStop.Color Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value representing the color of the gradient stop. Read-only.

Syntax

expression .Color

expression An expression that returns a GradientStop object.

Return Value

ColorFormat

Remarks

Gradients are a smooth transition from one color state to another. The endpoints of these sections are called stops.

See also

Concepts

GradientStop Object

Other resources

GradientStop Object Members


GradientStop.Creator Property (Office)

 Copy code hover
[image]

GradientStop.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the GradientStop object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a GradientStop object.

Return Value

Long

See also

Concepts

GradientStop Object

Other resources

GradientStop Object Members


GradientStop.Position Property (Office)

 Copy code hover
[image]

GradientStop.Position Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value representing the position of a stop within the gradient expressed as a percent. Read/write.

Syntax

expression .Position

expression An expression that returns a GradientStop object.

Return Value

Single

Remarks

Gradients are a smooth transition from one color state to another. The endpoints of these sections are called stops.

See also

Concepts

GradientStop Object

Other resources

GradientStop Object Members


GradientStop.Transparency Property (Office)

 Copy code hover
[image]

GradientStop.Transparency Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value representing the opacity of the gradient fill expressed as a percent. Read/write.

Syntax

expression .Transparency

expression An expression that returns a GradientStop object.

Return Value

Single

Remarks

Gradients are a smooth transition from one color state to another. The endpoints of these sections are called stops.

See also

Concepts

GradientStop Object

Other resources

GradientStop Object Members


GradientStops Object (Office)

 Copy code hover
[image]

GradientStops Object (Office)
See also Send feedback

Published: July 09, 2012

Contains a collection of GradientStop objects.

Remarks

Gradients are a smooth transition from one color state to another. The endpoints of these sections are called stops.

Example

The following example creates three color gradient stops in Microsoft PowerPoint.

VBA Copy code Copy code
Sub gradients()
 Set myDocument = ActivePresentation.Slides(1)
 Set GradientShapeFill = myDocument.Shapes.AddShape(msoShapeRectangle, 90, 90, 90, 80).Fill
 With GradientShapeFill
 .ForeColor.RGB = RGB(0, 128, 128)
 .OneColorGradient msoGradientHorizontal, 1, 1
 .GradientStops.Insert RGB(255, 0, 0), 0.25
 .GradientStops.Insert RGB(0, 255, 0), 0.5
 .GradientStops.Insert RGB(0, 0, 255), 0.75
 End With
End Sub

See also

Concepts

Object Model Reference

Other resources

GradientStops Object Members


GradientStops Members (Office)

 Copy code hover
[image]

GradientStops Members (Office)
Send feedback

Published: July 09, 2012

Contains a collection of GradientStop objects.

Methods

Name | Description
Delete | Removes a gradient stop.
Insert | Adds a stop to a gradient.
Insert2 | Adds a stop to a gradient and specifies the brightness, as well as the transparency, of the color.

Properties

Name | Description
Application | When used without an object qualifier, this property returns an Application object that represents the Microsoft Office application. When used with an object qualifier, this property returns an Application object that represents the creator of the specified object. Read-only.
Count | Gets a Long indicating the number of items in the GradientStops collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the GradientStops object was created. Read-only.
Item | Gets a GradientStop object from a GradientStops collection. Read-only.


GradientStops Properties (Office)

 Copy code hover
[image]

GradientStops Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | When used without an object qualifier, this property returns an Application object that represents the Microsoft Office application. When used with an object qualifier, this property returns an Application object that represents the creator of the specified object. Read-only.
Count | Gets a Long indicating the number of items in the GradientStops collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the GradientStops object was created. Read-only.
Item | Gets a GradientStop object from a GradientStops collection. Read-only.


GradientStops.Application Property (Office)

 Copy code hover
[image]

GradientStops.Application Property (Office)
See also Send feedback

Published: July 09, 2012

When used without an object qualifier, this property returns an Application object that represents the Microsoft Office application. When used with an object qualifier, this property returns an Application object that represents the creator of the specified object. Read-only.

Syntax

expression .Application

expression An expression that returns a GradientStops object.

Return Value

Object

Remarks

You can use this property with an OLE Automation object to return the application of that object.

See also

Concepts

GradientStops Object

Other resources

GradientStops Object Members


GradientStops.Count Property (Office)

 Copy code hover
[image]

GradientStops.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the GradientStops collection. Read-only.

Syntax

expression .Count

expression An expression that returns a GradientStops object.

Return Value

Integer

See also

Concepts

GradientStops Object

Other resources

GradientStops Object Members


GradientStops.Creator Property (Office)

 Copy code hover
[image]

GradientStops.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the GradientStops object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a GradientStops object.

Return Value

Long

See also

Concepts

GradientStops Object

Other resources

GradientStops Object Members


GradientStops.Item Property (Office)

 Copy code hover
[image]

GradientStops.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a GradientStop object from a GradientStops collection. Read-only.

Syntax

expression .Item(Index)

expression An expression that returns a GradientStops object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Integer | The name or index number of the object returned.

Return Value

GradientStop

See also

Concepts

GradientStops Object

Other resources

GradientStops Object Members


GradientStops Methods (Office)

 Copy code hover
[image]

GradientStops Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Removes a gradient stop.
Insert | Adds a stop to a gradient.
Insert2 | Adds a stop to a gradient and specifies the brightness, as well as the transparency, of the color.


GradientStops.Delete Method (Office)

 Copy code hover
[image]

GradientStops.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Removes a gradient stop.

Syntax

expression .Delete(Index)

expression An expression that returns a GradientStops object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Optional | Integer | The index number of the gradient stop.

Remarks

Gradients are a smooth transition from one color state to another. The endpoints of these sections are called stops.

Example

The following example adds three gradient color stops and then deletes the first gradient stop.

VBA Copy code Copy code
Sub gradients()
 Set myDocument = ActivePresentation.Slides(1)
 Set GradientShapeFill = myDocument.Shapes.AddShape(msoShapeRectangle, 90, 90, 90, 80).Fill
 With GradientShapeFill
 .ForeColor.RGB = RGB(0, 128, 128)
 .OneColorGradient msoGradientHorizontal, 1, 1
 .GradientStops.Insert RGB(255, 0, 0), 0.25
 .GradientStops.Insert RGB(0, 255, 0), 0.5
 .GradientStops.Insert RGB(0, 0, 255), 0.75
 End With
 GradientShapeFill.GradientStops.Delete (1)
End Sub

See also

Concepts

GradientStops Object

Other resources

GradientStops Object Members


GradientStops.Insert Method (Office)

 Copy code hover
[image]

GradientStops.Insert Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a stop to a gradient.

Syntax

expression .Insert(RGB, Position, Transparency, Index)

expression An expression that returns a GradientStops object.

Parameters

Name | Required/Optional | Data Type | Description
RGB | Required | MsoRGBType | Specifies the color at the gradient stop.
Position | Required | Single | Specifies the position of the stop within the gradient expressed as a percent.
Transparency | Optional | Single | Specifies the opacity of color at the gradient stop.
Index | Optional | Long | The index number of the stop.

Remarks

Gradients are a smooth transition from one color state to another. The endpoints of these sections are called stops.

Example

The following example creates three color gradient stops in Microsoft PowerPoint.

VBA Copy code Copy code
Sub gradients()
 Set myDocument = ActivePresentation.Slides(1)
 Set GradientShapeFill = myDocument.Shapes.AddShape(msoShapeRectangle, 90, 90, 90, 80).Fill
 With GradientShapeFill
 .ForeColor.RGB = RGB(0, 128, 128)
 .OneColorGradient msoGradientHorizontal, 1, 1
 .GradientStops.Insert RGB(255, 0, 0), 0.25
 .GradientStops.Insert RGB(0, 255, 0), 0.5
 .GradientStops.Insert RGB(0, 0, 255), 0.75
 End With
End Sub

See also

Concepts

GradientStops Object

Other resources

GradientStops Object Members


GradientStops.Insert2 Method (Office)

 Copy code hover
[image]

GradientStops.Insert2 Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a stop to a gradient and specifies the brightness, as well as the transparency, of the color.

Version Information

Version Added: Office 2010

Syntax

expression .Insert2(RGB, Position, Transparency, Index, Brightness)

expression An expression that returns a GradientStops object.

Parameters

Name | Required/Optional | Data Type | Description
RGB | Required | MsoRGBType | Specifies the color at the gradient stop.
Position | Required | Single | Specifies the position of the stop within the gradient expressed as a percent.
Transparency | Optional | Single | Specifies the opacity of the color at the gradient stop.
Index | Optional | Integer | The index number of the gradient stop.
Brightness | Optional | Single | Specifies the brightness of the color at the gradient stop.

Return Value

Nothing

Remarks

Gradients are a smooth transition from one color state to another. The endpoints of these sections are called stops.

This method differs from the Insert method in that it allows you to specify the brightness, as well as the transparency, of the color at the gradient stop.

See also

Concepts

GradientStops Object

Other resources

GradientStops Object Members


IAssistance Object (Office)

 Copy code hover
[image]

IAssistance Object (Office)
See also Send feedback

Published: July 09, 2012

Provides a means for developers to create a customized help experience for users within Microsoft Office.

Remarks

The Assistance property returns an IAssistance object. The IAssistance object exposes methods that allow developers to display help topics in the Office Help Viewer or to display help topics that ship with Office in the Help window of the host application. Developers either pass specific Help IDs to the help system or pass specific search queries. Help IDs have to be explicitly added to the Help file in order for the Help ID to return the help topic.

Example

In the first line in the following example, the ShowHelp method of the IAssistance object displays the help topic associated with the help ID "xlmain11.chm60407" in the "Excel" namespace. When the second line is executed, the client viewer will remain open and display the help topic associated with the help ID "65879", in the "Excel Developer" namespace.

VBA Copy code Copy code
Sub DisplayHelpTopic()
 Application.Assistance.ShowHelp "xlmain11.chm60407", ""
 Application.Assistance.ShowHelp "vbaxl10.chm65879", "DEV"
End Sub

See also

Concepts

Object Model Reference

Other resources

IAssistance Object Members


IAssistance Members (Office)

 Copy code hover
[image]

IAssistance Members (Office)
Send feedback

Published: July 09, 2012

Provides a means for developers to create a customized help experience for users within Microsoft Office.

Methods

Name | Description
ClearDefaultContext | Clears the default help topic previously defined in the SetDefaultContext method.
SearchHelp | Performs a search from the Office Help Viewer based on one or more keywords. Keywords can be a word or a phrase.
SetDefaultContext | Sets a help topic as the default topic that will be displayed when the user opens a help window.
ShowHelp | Displays the help topic specified by its ID in the Office Help Viewer or, for help topics that ship with Office, in the Help window of the current Office application.


IAssistance Methods (Office)

 Copy code hover
[image]

IAssistance Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
ClearDefaultContext | Clears the default help topic previously defined in the SetDefaultContext method.
SearchHelp | Performs a search from the Office Help Viewer based on one or more keywords. Keywords can be a word or a phrase.
SetDefaultContext | Sets a help topic as the default topic that will be displayed when the user opens a help window.
ShowHelp | Displays the help topic specified by its ID in the Office Help Viewer or, for help topics that ship with Office, in the Help window of the current Office application.


IAssistance.ClearDefaultContext Method (Office)

 Copy code hover
[image]

IAssistance.ClearDefaultContext Method (Office)
See also Send feedback

Published: July 09, 2012

Clears the default help topic previously defined in the SetDefaultContext method.

Syntax

expression .ClearDefaultContext(HelpId)

expression An expression that returns a IAssistance object.

Parameters

Name | Required/Optional | Data Type | Description
HelpId | Required | String | The ID of the default help topic.

Remarks

Executing this method will stop the default help topic from displaying when the user presses F1 or clicks the Help button in a dialog box.

The Assistance property returns an IAssistance object. The IAssistance object exposes methods that allow developers to display help topics in the Office Help Viewer or to display help topics that ship with Office in the Help window of the host application. Developers either pass specific Help IDs to the help system or pass specific search queries. Help IDs have to be explicitly added to the Help file in order for the Help ID to return the help topic.

Example

In the following example, the default help topic is cleared and will no longer displayed.

VBA Copy code Copy code
Sub ClearDefaultHelpTopic()
 Application.Assistance.ClearDefaultContext "22261"
End Sub

See also

Concepts

IAssistance Object

Other resources

IAssistance Object Members


IAssistance.SearchHelp Method (Office)

 Copy code hover
[image]

IAssistance.SearchHelp Method (Office)
See also Send feedback

Published: July 09, 2012

Performs a search from the Office Help Viewer based on one or more keywords. Keywords can be a word or a phrase.

Syntax

expression .SearchHelp(Query, Scope)

expression An expression that returns a IAssistance object.

Parameters

Name | Required/Optional | Data Type | Description
Query | Required | String | Represents the search keyword or phrase.
Scope | Optional | String | The namespace registered within the host application.

Remarks

The Assistance property returns an IAssistance object. The IAssistance object exposes methods that allow developers to display help topics in the Office Help Viewer or to display help topics that ship with Office in the Help window of the host application. Developers either pass specific Help IDs to the help system or pass specific search queries. Help IDs have to be explicitly added to the Help file in order for the Help ID to return the help topic.

The user can return more relevant help by narrowing the scope of the search, as long as the specified scope is applicable to the application. The following scopes are available within Microsoft Office applications. By default, the scope is set to the current application's namespace if a Null string ("") is passed as a parameter.

Example

In the first example, the search for "print a document" will be in the "Excel" namespace. In the second example, the search for "Application" will be in the "Excel Developer" namespace.

VBA Copy code Copy code
Sub SearchForHelpTopics1()
 Application.Assistance.SearchHelp "print a document", ""
End Sub

Sub SearchForHelpTopics2()
 Application.Assistance.SearchHelp "Application", "DEV"
End Sub

See also

Concepts

IAssistance Object

Other resources

IAssistance Object Members


IAssistance.SetDefaultContext Method (Office)

 Copy code hover
[image]

IAssistance.SetDefaultContext Method (Office)
See also Send feedback

Published: July 09, 2012

Sets a help topic as the default topic that will be displayed when the user opens a help window.

Syntax

expression .SetDefaultContext(HelpId)

expression An expression that returns a IAssistance object.

Parameters

Name | Required/Optional | Data Type | Description
HelpId | Required | String | The ID of the default help topic.

Remarks

The help topic specified in this method will not be displayed if Office has already defined a default help topic in that scope. In addition, for some dialog boxes, regardless of whether an ID is passed by the method, the help topic that shipped with Office will be displayed when the user presses the F1 key or clicks the Help button. For example, if the user is in a custom dialog box and presses F1, a custom or built-in help topic will be displayed if one is specified by the developer. If no default ID is specified, the default built-in Office help topic will be displayed. Likewise, if the user is in the New Document dialog box, for example, the Office specified help topic will be displayed regardless of whether a different ID is passed by the method.

The Assistance property returns an IAssistance object. The IAssistance object exposes methods that allow developers to display help topics in the Office Help Viewer or to display help topics that ship with Office in the Help window of the host application. Developers either pass specific Help IDs to the help system or pass specific search queries. Help IDs have to be explicitly added to the Help file in order for the Help ID to return the help topic.

Example

The following example, the help topic associated with ID "60385" will be set as the default for the application.

VBA Copy code Copy code
Sub SetDefaultHelpTopic()
 Application.Assistance.SetDefaultContext "60385"
End Sub

See also

Concepts

IAssistance Object

Other resources

IAssistance Object Members


IAssistance.ShowHelp Method (Office)

 Copy code hover
[image]

IAssistance.ShowHelp Method (Office)
See also Send feedback

Published: July 09, 2012

Displays the help topic specified by its ID in the Office Help Viewer or, for help topics that ship with Office, in the Help window of the current Office application.

Syntax

expression .ShowHelp(HelpId, Scope)

expression An expression that returns a IAssistance object.

Parameters

Name | Required/Optional | Data Type | Description
HelpId | Optional | String | The ID of the help topic.
Scope | Optional | String | The namespace registered within the host application.

Remarks

The Assistance property returns an IAssistance object. The IAssistance object exposes methods that allow developers to display help topics in the Office Help Viewer or to display help topics that ship with Office in the Help window of the host application. Developers either pass specific Help IDs to the help system or pass specific search queries. Help IDs have to be explicitly added to the Help file in order for the Help ID to return the help topic.

The following scopes are available within the Microsoft Office applications. By default, the scope is set to the current application's namespace if a Null string ("") is passed as a parameter.

Example

In the first line in the following example, the client help viewer will display the help topic associated with the ID "xlmain11.chm60407" in the "Excel" namespace. In the second line, the client viewer will remain open and display the help topic associated with the ID "65879", in the "Excel Developer" namespace.

VBA Copy code Copy code
Sub DisplayHelpTopic()
 Application.Assistance.ShowHelp "xlmain11.chm60407", ""
 Application.Assistance.ShowHelp "vbaxl10.chm65879", "DEV"
End Sub

See also

Concepts

IAssistance Object

Other resources

IAssistance Object Members


IBlogExtensibility Object (Office)

 Copy code hover
[image]

IBlogExtensibility Object (Office)
See also Send feedback

Published: July 09, 2012

An object that provides the ability to manipulate blog entries.

See also

Concepts

Object Model Reference

Other resources

IBlogExtensibility Object Members


IBlogExtensibility Members (Office)

 Copy code hover
[image]

IBlogExtensibility Members (Office)
Send feedback

Published: July 09, 2012

An object that provides the ability to manipulate blog entries.

Methods

Name | Description
BlogProviderProperties | Contains information about the provider.
GetCategories | This method returns the list of blog categories for an account so Microsoft Word can populate the categories dropdown list.
GetRecentPosts | Returns the list of the user's last fifteen blog posts that Microsoft Word then displays in the Open Existing Post dialog. This method does not actually return the blog post contents.
GetUserBlogs | Returns the list and details of user blogs associated with the specified account.
Open | Opens the blog specified by the blog ID. It is called by the Open Existing Post dialog based on the item selected by the user.
PublishPost | Hands off the current post so it can be published by the provider.
RepublishPost | Hands off the current post so it can be republished by the provider.
SetupBlogAccount | Called from the Choose Account dialog when the provider's name is chosen in the Blog Host dropdown or when the user requests to change a provider's account in the Blog Accounts dialog box.


IBlogExtensibility Methods (Office)

 Copy code hover
[image]

IBlogExtensibility Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
BlogProviderProperties | Contains information about the provider.
GetCategories | This method returns the list of blog categories for an account so Microsoft Word can populate the categories dropdown list.
GetRecentPosts | Returns the list of the user's last fifteen blog posts that Microsoft Word then displays in the Open Existing Post dialog. This method does not actually return the blog post contents.
GetUserBlogs | Returns the list and details of user blogs associated with the specified account.
Open | Opens the blog specified by the blog ID. It is called by the Open Existing Post dialog based on the item selected by the user.
PublishPost | Hands off the current post so it can be published by the provider.
RepublishPost | Hands off the current post so it can be republished by the provider.
SetupBlogAccount | Called from the Choose Account dialog when the provider's name is chosen in the Blog Host dropdown or when the user requests to change a provider's account in the Blog Accounts dialog box.


IBlogExtensibility.BlogProviderProperties Method (Office)

 Copy code hover
[image]

IBlogExtensibility.BlogProviderProperties Method (Office)
See also Send feedback

Published: July 09, 2012

Contains information about the provider.

Syntax

expression .BlogProviderProperties(BlogProvider, FriendlyName, CategorySupport, Padding, NoCredentials)

expression An expression that returns a IBlogExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
BlogProvider | Required | String | The name of the blog provider.
FriendlyName | Required | String | Represents the name displayed in the user interface.
CategorySupport | Required | MsoBlogCategorySupport | Represents how many categories are supported by the provider.
Padding | Required | Boolean | Specifies whether table padding is recognized.
NoCredentials | Required | Boolean | Specifies whether credentials are required by the provider.

See also

Concepts

IBlogExtensibility Object

Other resources

IBlogExtensibility Object Members


IBlogExtensibility.GetCategories Method (Office)

 Copy code hover
[image]

IBlogExtensibility.GetCategories Method (Office)
See also Send feedback

Published: July 09, 2012

This method returns the list of blog categories for an account so Microsoft Word can populate the categories dropdown list.

Syntax

expression .GetCategories(Account, ParentWindow, Document, userName, Password, Categories())

expression An expression that returns a IBlogExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
Account | Required | String | Represents the GUID of the account registry key.
ParentWindow | Required | Long | Represents the HWND of the host window.
Document | Required | Object | The current document.
userName | Required | String | Represents the username stored in the registry account settings.
Password | Required | String | Represents user's password stored in the registry account settings.
Categories() | Required | String | A list of categories supported by the provider.

Remarks

Blog account settings are stored in the registry at \\HKCU\Software\Microsoft\Office\Common\Blog\Account.

See also

Concepts

IBlogExtensibility Object

Other resources

IBlogExtensibility Object Members


IBlogExtensibility.GetRecentPosts Method (Office)

 Copy code hover
[image]

IBlogExtensibility.GetRecentPosts Method (Office)
See also Send feedback

Published: July 09, 2012

Returns the list of the user's last fifteen blog posts that Microsoft Word then displays in the Open Existing Post dialog. This method does not actually return the blog post contents.

Syntax

expression .GetRecentPosts(Account, ParentWindow, Document, userName, Password, PostTitles(), PostDates(), PostIDs())

expression An expression that returns a IBlogExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
Account | Required | String | Represents the GUID of the account registry key. Blog account settings are stored in the registry at \\HKCU\Software\Microsoft\Office\Common\Blog\Account.
ParentWindow | Required | Long | Contains the HWND for the window Microsoft Word is calling from.
Document | Required | Object | The current document.
userName | Required | String | Represents the username stored in the registry account settings.
Password | Required | String | Represents user's password stored in the registry account settings.
PostTitles() | Required | String | Contains the titles of the last fifteen posts.
PostDates() | Required | String | Contains the dates of the last fifteen posts.
PostIDs() | Required | String | Contains the IDs of the last fifteen posts.

See also

Concepts

IBlogExtensibility Object

Other resources

IBlogExtensibility Object Members


IBlogExtensibility.GetUserBlogs Method (Office)

 Copy code hover
[image]

IBlogExtensibility.GetUserBlogs Method (Office)
See also Send feedback

Published: July 09, 2012

Returns the list and details of user blogs associated with the specified account.

Syntax

expression .GetUserBlogs(Account, ParentWindow, Document, userName, Password, BlogNames(), BlogIDs(), BlogURLs())

expression An expression that returns a IBlogExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
Account | Required | String | Represents the GUID of the account registry key. Blog account settings are stored in the registry at \\HKCU\Software\Microsoft\Office\Common\Blog\Account.
ParentWindow | Required | Long | Contains the HWND for the window Microsoft Word is calling from.
Document | Required | Object | The current document.
userName | Required | String | Represents the username stored in the registry account settings.
Password | Required | String | Represents user's password stored in the registry account settings.
BlogNames() | Required | String | Contains all blog names under the current account.
BlogIDs() | Required | String | Contains all blog IDs under the current account.
BlogURLs() | Required | String | Contains all blog URLs under the current account.

See also

Concepts

IBlogExtensibility Object

Other resources

IBlogExtensibility Object Members


IBlogExtensibility.Open Method (Office)

 Copy code hover
[image]

IBlogExtensibility.Open Method (Office)
See also Send feedback

Published: July 09, 2012

Opens the blog specified by the blog ID. It is called by the Open Existing Post dialog based on the item selected by the user.

Syntax

expression .Open(Account, PostID, ParentWindow, userName, Password, xHTML, Title, DatePosted, Categories())

expression An expression that returns a IBlogExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
Account | Required | String | Represents the GUID of the account registry key. Blog account settings are stored in the registry at \\HKCU\Software\Microsoft\Office\Common\Blog\Account.
PostID | Required | String | The ID of the post.
ParentWindow | Required | Long | Contains the HWND for the window Microsoft Word is calling from.
userName | Required | String | Represents the username stored in the registry account settings.
Password | Required | String | Represents user's password stored in the registry account settings.
xHTML | Required | String | Represents the xHTML of the current document.
Title | Required | String | The title of the post.
DatePosted | Required | String | The date the entry was posted.
Categories() | Required | String | A list of categories supported by the provider.

See also

Concepts

IBlogExtensibility Object

Other resources

IBlogExtensibility Object Members


IBlogExtensibility.PublishPost Method (Office)

 Copy code hover
[image]

IBlogExtensibility.PublishPost Method (Office)
See also Send feedback

Published: July 09, 2012

Hands off the current post so it can be published by the provider.

Syntax

expression .PublishPost(Account, ParentWindow, Document, userName, Password, xHTML, Title, DateTime, Categories(), Draft, PostID, PublishMessage)

expression An expression that returns a IBlogExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
Account | Required | String | Represents the GUID of the account registry key. Blog account settings are stored in the registry at \\HKCU\Software\Microsoft\Office\Common\Blog\Account.
ParentWindow | Required | Long | Contains the HWND for the window Microsoft Word is calling from.
Document | Required | Object | The current document.
userName | Required | String | Represents the username stored in the registry account settings.
Password | Required | String | Represents user's password stored in the registry account settings.
xHTML | Required | String | Represents the xHTML of the current document.
Title | Required | String | The title of the post.
DateTime | Required | String | The date the entry was posted.
Categories() | Required | String | A list of categories supported by the provider.
Draft | Required | Boolean | Specifies whether this is a draft version of the post.
PostID | Required | String | The ID of the original post if this post has been republished.
PublishMessage | Required | String | Specifies what is displayed in the publish bar.

See also

Concepts

IBlogExtensibility Object

Other resources

IBlogExtensibility Object Members


IBlogExtensibility.RepublishPost Method (Office)

 Copy code hover
[image]

IBlogExtensibility.RepublishPost Method (Office)
See also Send feedback

Published: July 09, 2012

Hands off the current post so it can be republished by the provider.

Syntax

expression .RepublishPost(Account, ParentWindow, Document, userName, Password, PostID, xHTML, Title, DateTime, Categories(), Draft, PublishMessage)

expression An expression that returns a IBlogExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
Account | Required | String | Represents the GUID of the account registry key. Blog account settings are stored in the registry at \\HKCU\Software\Microsoft\Office\Common\Blog\Account.
ParentWindow | Required | Long | Contains the HWND for the window Microsoft Word is calling from.
Document | Required | Object | The current document.
userName | Required | String | Represents the username stored in the registry account settings.
Password | Required | String | Represents user's password stored in the registry account settings.
PostID | Required | String | The ID of the original post.
xHTML | Required | String | Represents the xHTML of the current document.
Title | Required | String | The title of the post.
DateTime | Required | String | The date the entry was posted.
Categories() | Required | String | A list of categories supported by the provider.
Draft | Required | Boolean | Specifies whether this is a draft version of the post.
PublishMessage | Required | String | Specifies what is displayed in the publish bar.

See also

Concepts

IBlogExtensibility Object

Other resources

IBlogExtensibility Object Members


IBlogExtensibility.SetupBlogAccount Method (Office)

 Copy code hover
[image]

IBlogExtensibility.SetupBlogAccount Method (Office)
See also Send feedback

Published: July 09, 2012

Called from the Choose Account dialog when the provider's name is chosen in the Blog Host dropdown or when the user requests to change a provider's account in the Blog Accounts dialog box.

Syntax

expression .SetupBlogAccount(Account, ParentWindow, Document, NewAccount, ShowPictureUI)

expression An expression that returns a IBlogExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
Account | Required | String | Represents the GUID of the account registry key. Blog account settings are stored in the registry at \\HKCU\Software\Microsoft\Office\Common\Blog\Account.
ParentWindow | Required | Long | Contains the HWND for the window Microsoft Word is calling from.
Document | Required | Object | The current document.
NewAccount | Required | Boolean | Indicates whether this is a new account.
ShowPictureUI | Required | Boolean | Indicates whether Microsoft Word's picture user interface needs to be displayed.

See also

Concepts

IBlogExtensibility Object

Other resources

IBlogExtensibility Object Members


IBlogPictureExtensibility Object (Office)

 Copy code hover
[image]

IBlogPictureExtensibility Object (Office)
See also Send feedback

Published: July 09, 2012

Represents an object that provides the ability to manipulate blog images.

Remarks

Pictures are stored with picture providers in an account set up by the user.

See also

Concepts

Object Model Reference

Other resources

IBlogPictureExtensibility Object Members


IBlogPictureExtensibility Members (Office)

 Copy code hover
[image]

IBlogPictureExtensibility Members (Office)
Send feedback

Published: July 09, 2012

Represents an object that provides the ability to manipulate blog images.

Methods

Name | Description
BlogPictureProviderProperties | Enables picture providers to offer themselves as an upload location for blog pictures.
CreatePictureAccount | Allows a picture provider to display the user interface needed to guide the user through setting up a picture account.
PublishPicture | Used to post a picture object to its final destination in a blog.


IBlogPictureExtensibility Methods (Office)

 Copy code hover
[image]

IBlogPictureExtensibility Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
BlogPictureProviderProperties | Enables picture providers to offer themselves as an upload location for blog pictures.
CreatePictureAccount | Allows a picture provider to display the user interface needed to guide the user through setting up a picture account.
PublishPicture | Used to post a picture object to its final destination in a blog.


IBlogPictureExtensibility.BlogPictureProviderProperties Method (Office)

 Copy code hover
[image]

IBlogPictureExtensibility.BlogPictureProviderProperties Method (Office)
See also Send feedback

Published: July 09, 2012

Enables picture providers to offer themselves as an upload location for blog pictures.

Syntax

expression .BlogPictureProviderProperties(BlogPictureProvider, FriendlyName)

expression An expression that returns a IBlogPictureExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
BlogPictureProvider | Required | String | The ID of the picture provider.
FriendlyName | Required | String | The friendly name of the picture provider.

See also

Concepts

IBlogPictureExtensibility Object

Other resources

IBlogPictureExtensibility Object Members


IBlogPictureExtensibility.CreatePictureAccount Method (Office)

 Copy code hover
[image]

IBlogPictureExtensibility.CreatePictureAccount Method (Office)
See also Send feedback

Published: July 09, 2012

Allows a picture provider to display the user interface needed to guide the user through setting up a picture account.

Syntax

expression .CreatePictureAccount(Account, BlogProvider, ParentWindow, Document, userName, Password)

expression An expression that returns a IBlogPictureExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
Account | Required | String | Represents the GUID of the account registry key. Blog account settings are stored in the registry at \\HKCU\Software\Microsoft\Office\Common\Blog\Account.
BlogProvider | Required | String | The ID of the provider.
ParentWindow | Required | Long | Contains the HWND for the window Microsoft Word is calling from.
Document | Required | Object | The current document.
userName | Required | String | Represents the username stored in the registry account settings.
Password | Required | String | Represents user's password stored in the registry account settings.

See also

Concepts

IBlogPictureExtensibility Object

Other resources

IBlogPictureExtensibility Object Members


IBlogPictureExtensibility.PublishPicture Method (Office)

 Copy code hover
[image]

IBlogPictureExtensibility.PublishPicture Method (Office)
See also Send feedback

Published: July 09, 2012

Used to post a picture object to its final destination in a blog.

Syntax

expression .PublishPicture(Account, ParentWindow, Document, userName, Password, Image, PictureURI)

expression An expression that returns a IBlogPictureExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
Account | Required | String | Represents the GUID of the account registry key. Blog account settings are stored in the registry at \\HKCU\Software\Microsoft\Office\Common\Blog\Account.
ParentWindow | Required | Long | Contains the HWND for the window Microsoft Word is calling from.
Document | Required | Object | The current document.
userName | Required | String | Represents the username stored in the registry account settings.
Password | Required | String | Represents user's password stored in the registry account settings.
Image | Required | Unknown | Represents the name of the image file.
PictureURI | Required | String | The URI of the picture.

Remarks

This method is called during xHTML generation and hands off a .PNG representation of the picture. The location where it was published is then returned which is then added to an IMG tag in the xHTML output.

See also

Concepts

IBlogPictureExtensibility Object

Other resources

IBlogPictureExtensibility Object Members


IConverter Object (Office)

 Copy code hover
[image]

IConverter Object (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

See also

Concepts

Object Model Reference

Other resources

IConverter Object Members


IConverter Members (Office)

 Copy code hover
[image]

IConverter Members (Office)
Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Methods

Name | Description
HrExport | This feature is only available in the Open XML Format SDK.
HrGetErrorString | This feature is only available in the Open XML Format SDK.
HrGetFormat | This feature is only available in the Open XML Format SDK.
HrImport | This feature is only available in the Open XML Format SDK.
HrInitConverter | This feature is only available in the Open XML Format SDK.
HrUninitConverter | This feature is only available in the Open XML Format SDK.


IConverter Methods (Office)

 Copy code hover
[image]

IConverter Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
HrExport | This feature is only available in the Open XML Format SDK.
HrGetErrorString | This feature is only available in the Open XML Format SDK.
HrGetFormat | This feature is only available in the Open XML Format SDK.
HrImport | This feature is only available in the Open XML Format SDK.
HrInitConverter | This feature is only available in the Open XML Format SDK.
HrUninitConverter | This feature is only available in the Open XML Format SDK.


IConverter.HrExport Method (Office)

 Copy code hover
[image]

IConverter.HrExport Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrExport(bstrSourcePath, bstrDestPath, bstrClass, pcap, ppcp, pcuic)

expression An expression that returns a IConverter object.

Parameters

Name | Required/Optional | Data Type | Description
bstrSourcePath | Required | String |
bstrDestPath | Required | String |
bstrClass | Required | String |
pcap | Required | IConverterApplicationPreferences |
ppcp | Required | IConverterPreferences |
pcuic | Required | IConverterUICallback |

Return Value

[HRESULT]

See also

Concepts

IConverter Object

Other resources

IConverter Object Members


IConverter.HrGetErrorString Method (Office)

 Copy code hover
[image]

IConverter.HrGetErrorString Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrGetErrorString(hrErr, pbstrErrorMsg, pcap)

expression An expression that returns a IConverter object.

Parameters

Name | Required/Optional | Data Type | Description
hrErr | Required | Long |
pbstrErrorMsg | Required | String |
pcap | Required | IConverterApplicationPreferences |

Return Value

[HRESULT]

See also

Concepts

IConverter Object

Other resources

IConverter Object Members


IConverter.HrGetFormat Method (Office)

 Copy code hover
[image]

IConverter.HrGetFormat Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrGetFormat(bstrPath, pbstrClass, pcap, ppcp, pcuic)

expression An expression that returns a IConverter object.

Parameters

Name | Required/Optional | Data Type | Description
bstrPath | Required | String |
pbstrClass | Required | String |
pcap | Required | IConverterApplicationPreferences |
ppcp | Required | IConverterPreferences |
pcuic | Required | IConverterUICallback |

Return Value

[HRESULT]

See also

Concepts

IConverter Object

Other resources

IConverter Object Members


IConverter.HrImport Method (Office)

 Copy code hover
[image]

IConverter.HrImport Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrImport(bstrSourcePath, bstrDestPath, pcap, ppcp, pcuic)

expression An expression that returns a IConverter object.

Parameters

Name | Required/Optional | Data Type | Description
bstrSourcePath | Required | String |
bstrDestPath | Required | String |
pcap | Required | IConverterApplicationPreferences |
ppcp | Required | IConverterPreferences |
pcuic | Required | IConverterUICallback |

Return Value

[HRESULT]

See also

Concepts

IConverter Object

Other resources

IConverter Object Members


IConverter.HrInitConverter Method (Office)

 Copy code hover
[image]

IConverter.HrInitConverter Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrInitConverter(pcap, ppcp, pcuic)

expression An expression that returns a IConverter object.

Parameters

Name | Required/Optional | Data Type | Description
pcap | Required | IConverterApplicationPreferences |
ppcp | Required | IConverterPreferences |
pcuic | Required | IConverterUICallback |

Return Value

[HRESULT]

See also

Concepts

IConverter Object

Other resources

IConverter Object Members


IConverter.HrUninitConverter Method (Office)

 Copy code hover
[image]

IConverter.HrUninitConverter Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrUninitConverter(pcuic)

expression An expression that returns a IConverter object.

Parameters

Name | Required/Optional | Data Type | Description
pcuic | Required | IConverterUICallback |

Return Value

[HRESULT]

See also

Concepts

IConverter Object

Other resources

IConverter Object Members


IConverterApplicationPreferences Object (Office)

 Copy code hover
[image]

IConverterApplicationPreferences Object (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

See also

Concepts

Object Model Reference

Other resources

IConverterApplicationPreferences Object Members


IConverterApplicationPreferences Members (Office)

 Copy code hover
[image]

IConverterApplicationPreferences Members (Office)
Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Methods

Name | Description
HrCheckFormat | This feature is only available in the Open XML Format SDK.
HrGetApplication | This feature is only available in the Open XML Format SDK.
HrGetHwnd | This feature is only available in the Open XML Format SDK.
HrGetLcid | This feature is only available in the Open XML Format SDK.


IConverterApplicationPreferences Methods (Office)

 Copy code hover
[image]

IConverterApplicationPreferences Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
HrCheckFormat | This feature is only available in the Open XML Format SDK.
HrGetApplication | This feature is only available in the Open XML Format SDK.
HrGetHwnd | This feature is only available in the Open XML Format SDK.
HrGetLcid | This feature is only available in the Open XML Format SDK.


IConverterApplicationPreferences.HrCheckFormat Method (Office)

 Copy code hover
[image]

IConverterApplicationPreferences.HrCheckFormat Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrCheckFormat(pFormat)

expression An expression that returns a IConverterApplicationPreferences object.

Parameters

Name | Required/Optional | Data Type | Description
pFormat | Required | [INT] |

Return Value

[HRESULT]

See also

Concepts

IConverterApplicationPreferences Object

Other resources

IConverterApplicationPreferences Object Members


IConverterApplicationPreferences.HrGetApplication Method (Office)

 Copy code hover
[image]

IConverterApplicationPreferences.HrGetApplication Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrGetApplication(pbstrApplication)

expression An expression that returns a IConverterApplicationPreferences object.

Parameters

Name | Required/Optional | Data Type | Description
pbstrApplication | Required | String |

Return Value

[HRESULT]

See also

Concepts

IConverterApplicationPreferences Object

Other resources

IConverterApplicationPreferences Object Members


IConverterApplicationPreferences.HrGetHwnd Method (Office)

 Copy code hover
[image]

IConverterApplicationPreferences.HrGetHwnd Method (Office)
See also Send feedback

Published: July 16, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrGetHwnd(phwnd)

expression An expression that returns a IConverterApplicationPreferences object.

Parameters

Name | Required/Optional | Data Type | Description
phwnd | Required | Long |

Return Value

[HRESULT]

See also

Concepts

IConverterApplicationPreferences Object

Other resources

IConverterApplicationPreferences Object Members


IConverterApplicationPreferences.HrGetLcid Method (Office)

 Copy code hover
[image]

IConverterApplicationPreferences.HrGetLcid Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrGetLcid(plcid)

expression An expression that returns a IConverterApplicationPreferences object.

Parameters

Name | Required/Optional | Data Type | Description
plcid | Required | [UINT32] |

Return Value

[HRESULT]

See also

Concepts

IConverterApplicationPreferences Object

Other resources

IConverterApplicationPreferences Object Members


IConverterPreferences Object (Office)

 Copy code hover
[image]

IConverterPreferences Object (Office)
See also Send feedback

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

See also

Concepts

Object Model Reference

Other resources

IConverterPreferences Object Members


IConverterPreferences Members (Office)

 Copy code hover
[image]

IConverterPreferences Members (Office)
Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Methods

Name | Description
HrCheckFormat | This feature is only available in the Open XML Format SDK.
HrGetLossySave | This feature is only available in the Open XML Format SDK.
HrGetMacroEnabled | This feature is only available in the Open XML Format SDK.


IConverterPreferences Methods (Office)

 Copy code hover
[image]

IConverterPreferences Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
HrCheckFormat | This feature is only available in the Open XML Format SDK.
HrGetLossySave | This feature is only available in the Open XML Format SDK.
HrGetMacroEnabled | This feature is only available in the Open XML Format SDK.


IConverterPreferences.HrCheckFormat Method (Office)

 Copy code hover
[image]

IConverterPreferences.HrCheckFormat Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrCheckFormat(pFormat)

expression An expression that returns a IConverterPreferences object.

Parameters

Name | Required/Optional | Data Type | Description
pFormat | Required | [INT] |

Return Value

[HRESULT]

See also

Concepts

IConverterPreferences Object

Other resources

IConverterPreferences Object Members


IConverterPreferences.HrGetLossySave Method (Office)

 Copy code hover
[image]

IConverterPreferences.HrGetLossySave Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrGetLossySave(pfLossySave)

expression An expression that returns a IConverterPreferences object.

Parameters

Name | Required/Optional | Data Type | Description
pfLossySave | Required | [INT] |

Return Value

[HRESULT]

See also

Concepts

IConverterPreferences Object

Other resources

IConverterPreferences Object Members


IConverterPreferences.HrGetMacroEnabled Method (Office)

 Copy code hover
[image]

IConverterPreferences.HrGetMacroEnabled Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrGetMacroEnabled(pfMacroEnabled)

expression An expression that returns a IConverterPreferences object.

Parameters

Name | Required/Optional | Data Type | Description
pfMacroEnabled | Required | [INT] |

Return Value

[HRESULT]

See also

Concepts

IConverterPreferences Object

Other resources

IConverterPreferences Object Members


IConverterUICallback Object (Office)

 Copy code hover
[image]

IConverterUICallback Object (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

See also

Concepts

Object Model Reference

Other resources

IConverterUICallback Object Members


IConverterUICallback Members (Office)

 Copy code hover
[image]

IConverterUICallback Members (Office)
Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Methods

Name | Description
HrInputBox | This feature is only available in the Open XML Format SDK.
HrMessageBox | This feature is only available in the Open XML Format SDK.
HrReportProgress | This feature is only available in the Open XML Format SDK.


IConverterUICallback Methods (Office)

 Copy code hover
[image]

IConverterUICallback Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
HrInputBox | This feature is only available in the Open XML Format SDK.
HrMessageBox | This feature is only available in the Open XML Format SDK.
HrReportProgress | This feature is only available in the Open XML Format SDK.


IConverterUICallback.HrInputBox Method (Office)

 Copy code hover
[image]

IConverterUICallback.HrInputBox Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrInputBox(bstrText, bstrCaption, pbstrInput, fPassword)

expression An expression that returns a IConverterUICallback object.

Parameters

Name | Required/Optional | Data Type | Description
bstrText | Required | String |
bstrCaption | Required | String |
pbstrInput | Required | String |
fPassword | Required | [INT] |

Return Value

[HRESULT]

See also

Concepts

IConverterUICallback Object

Other resources

IConverterUICallback Object Members


IConverterUICallback.HrMessageBox Method (Office)

 Copy code hover
[image]

IConverterUICallback.HrMessageBox Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrMessageBox(bstrText, bstrCaption, uType, pidResult)

expression An expression that returns a IConverterUICallback object.

Parameters

Name | Required/Optional | Data Type | Description
bstrText | Required | String |
bstrCaption | Required | String |
uType | Required | [UINT] |
pidResult | Required | [INT] |

Return Value

[HRESULT]

See also

Concepts

IConverterUICallback Object

Other resources

IConverterUICallback Object Members


IConverterUICallback.HrReportProgress Method (Office)

 Copy code hover
[image]

IConverterUICallback.HrReportProgress Method (Office)
See also Send feedback

Published: July 09, 2012

This feature is only available in the Open XML Format SDK.

Version Information

Version Added: Office 2010

Syntax

expression .HrReportProgress(uPercentComplete)

expression An expression that returns a IConverterUICallback object.

Parameters

Name | Required/Optional | Data Type | Description
uPercentComplete | Required | [UINT] |

Return Value

[HRESULT]

See also

Concepts

IConverterUICallback Object

Other resources

IConverterUICallback Object Members


ICTPFactory Object (Office)

 Copy code hover
[image]

ICTPFactory Object (Office)
See also Send feedback

Published: July 09, 2012

Used to create a custom task pane.

Example

The following example, written in C#, creates an instance of a CustomTaskPane object and implements its only method, CTPFactoryAvailable. CTPFactoryAvailable passes an ICTPFactory object to the add-in, which you can use during the add-in's lifetime to create a task pane by using the CreateCTP method. Note that the example assumes that the task pane is part of an COM add-in and thus implements Extensibility.IDTExtensibility2. The add-in also references a Microsoft ActiveX® control, SampleActiveX.myControl, that is created in a separate project.

Copy code Copy code
public class Connect : Object, Extensibility.IDTExtensibility2, ICustomTaskPaneConsumer
...
object missing = Type.Missing;
public CustomTaskPane CTP = null;

public void CTPFactoryAvailable(ICTPFactory CTPFactoryInst)
{
 CTP = CTPFactoryInst.CreateCTP("SampleActiveX.myControl", "Task Pane Example", missing);
 sampleAX = (myControl)CTP.ContentControl;
 sampleAX.InsertTextClicked += new InsertTextEventHandler(sampleAX_InsertTextClicked);
 CTP.Visible = true;
}
...
Note Note

You can create custom task panes in any language that supports COM and allows you to create dynamic-linked library (DLL) files. For example, Microsoft Visual Basic® 6.0, Microsoft Visual Basic .NET, Microsoft Visual C++®, Microsoft Visual C++ .NET, and Microsoft Visual C#®. However, Microsoft Visual Basic for Applications (VBA) does not support creating custom task panes.

See also

Concepts

Object Model Reference

Other resources

ICTPFactory Object Members


ICTPFactory Members (Office)

 Copy code hover
[image]

ICTPFactory Members (Office)
Send feedback

Published: July 09, 2012

Used to create a custom task pane.

Methods

Name | Description
CreateCTP | Creates an instance of a custom task pane.


ICTPFactory Methods (Office)

 Copy code hover
[image]

ICTPFactory Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
CreateCTP | Creates an instance of a custom task pane.


ICTPFactory.CreateCTP Method (Office)

 Copy code hover
[image]

ICTPFactory.CreateCTP Method (Office)
See also Send feedback

Published: July 09, 2012

Creates an instance of a custom task pane.

Syntax

expression .CreateCTP(CTPAxID, CTPTitle, CTPParentWindow)

expression An expression that returns a ICTPFactory object.

Parameters

Name | Required/Optional | Data Type | Description
CTPAxID | Required | String | The CLSID or ProgID of a Microsoft ActiveX® object.
CTPTitle | Required | String | The title for the task pane.
CTPParentWindow | Optional | Variant | The window that hosts the task pane. If not present, the parent of the task pane is the ActiveWindow of the host application.

Return Value

CustomTaskPane

Example

The following example, written in C#, creates an instance of a CustomTaskPane object through the ICustomTaskPaneConsumer interface and implements its only method, CTPFactoryAvailable. CTPFactoryAvailable passes a CTPFactory object to the add-in, which you can use during the add-in's lifetime to create task panes by using the CreateCTP method. Note that the example assumes that the task pane is part of an COM add-in and thus implements Extensibility.IDTExtensibility2. The add-in also references an ActiveX control, SampleActiveX.myControl, that was created in a separate project.

Copy code Copy code
public class Connect : Object, Extensibility.IDTExtensibility2, ICustomTaskPaneConsumer
...
object missing = Type.Missing;
public CustomTaskPane CTP = null;

public void CTPFactoryAvailable(ICTPFactory CTPFactoryInst)
{
 CTP = CTPFactoryInst.CreateCTP("SampleActiveX.myControl", "Task Pane Example", missing);
 sampleAX = (myControl)CTP.ContentControl;
 sampleAX.InsertTextClicked += new InsertTextEventHandler(sampleAX_InsertTextClicked);
 CTP.Visible = true;
}
Note Note

You can create custom task panes in any language that supports COM and allows you to create dynamic-linked library (DLL) files. For example, Microsoft Visual Basic® 6.0, Microsoft Visual Basic .NET, Microsoft Visual C++®, Microsoft Visual C++ .NET, and Microsoft Visual C#®. However, Microsoft Visual Basic for Applications (VBA) does not support creating custom task panes.

See also

Concepts

ICTPFactory Object

Other resources

ICTPFactory Object Members


ICustomTaskPaneConsumer Object (Office)

 Copy code hover
[image]

ICustomTaskPaneConsumer Object (Office)
See also Send feedback

Published: July 09, 2012

An interface that provides access to the CTPFactoryAvailable method that is used to create an instance of a custom task pane.

Example

The following example, written in C#, creates an instance of a CustomTaskPane object through the ICustomTaskPaneConsumer interface and implements its only method, CTPFactoryAvailable. CTPFactoryAvailable passes an CTPFactory object to the add-in, which you can use during the add-in's lifetime to create task panes by using the CreateCTP method. Note that the example assumes that the task pane is part of an COM add-in and thus implements Extensibility.IDTExtensibility2. The add-in also references a Microsoft ActiveX® control, SampleActiveX.myControl, that is created in a separate project.

Copy code Copy code
public class Connect : Object, Extensibility.IDTExtensibility2, ICustomTaskPaneConsumer
...
object missing = Type.Missing;
public CustomTaskPane CTP = null;

public void CTPFactoryAvailable(ICTPFactory CTPFactoryInst)
{
 CTP = CTPFactoryInst.CreateCTP("SampleActiveX.myControl", "Task Pane Example", missing);
 sampleAX = (myControl)CTP.ContentControl;
 sampleAX.InsertTextClicked += new InsertTextEventHandler(sampleAX_InsertTextClicked);
 CTP.Visible = true;
}
...
Note Note

You can create custom task panes in any language that supports COM and allows you to create dynamic-linked library (DLL) files. For example, Microsoft Visual Basic® 6.0, Microsoft Visual Basic .NET, Microsoft Visual C++®, Microsoft Visual C++ .NET, and Microsoft Visual C#®. However, Microsoft Visual Basic for Applications (VBA) does not support creating custom task panes.

See also

Concepts

Object Model Reference

Other resources

ICustomTaskPaneConsumer Object Members


ICustomTaskPaneConsumer Members (Office)

 Copy code hover
[image]

ICustomTaskPaneConsumer Members (Office)
Send feedback

Published: July 09, 2012

An interface that provides access to the CTPFactoryAvailable method that is used to create an instance of a custom task pane.

Methods

Name | Description
CTPFactoryAvailable | Passes an CTPFactory object to a Microsoft ActiveX add-in that can then used when creating a custom task pane.


ICustomTaskPaneConsumer Methods (Office)

 Copy code hover
[image]

ICustomTaskPaneConsumer Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
CTPFactoryAvailable | Passes an CTPFactory object to a Microsoft ActiveX add-in that can then used when creating a custom task pane.


ICustomTaskPaneConsumer.CTPFactoryAvailable Method (Office)

 Copy code hover
[image]

ICustomTaskPaneConsumer.CTPFactoryAvailable Method (Office)
See also Send feedback

Published: July 09, 2012

Passes an CTPFactory object to a Microsoft ActiveX add-in that can then used when creating a custom task pane.

Syntax

expression .CTPFactoryAvailable(CTPFactoryInst)

expression An expression that returns a ICustomTaskPaneConsumer object.

Parameters

Name | Required/Optional | Data Type | Description
CTPFactoryInst | Required | ICTPFactory | The object is used by an add-in to create a task pane.

Example

The following example, written in C#, creates an instance of a CustomTaskPane object through the ICustomTaskPaneConsumer interface and implements its only method, CTPFactoryAvailable. CTPFactoryAvailable passes an CTPFactory object to the add-in, which you can use during the add-in's lifetime to create a task pane by using the CreateCTP method. Note that the example assumes that the task pane is part of an COM add-in and thus implements Extensibility.IDTExtensibility2. The add-in also refers to an ActiveX control, SampleActiveX.myControl, that was created in a separate project.

Copy code Copy code
public class Connect : Object, Extensibility.IDTExtensibility2, ICustomTaskPaneConsumer
...
object missing = Type.Missing;
public CustomTaskPane CTP = null;

public void CTPFactoryAvailable(ICTPFactory CTPFactoryInst)
{
 CTP = CTPFactoryInst.CreateCTP("SampleActiveX.myControl", "Task Pane Example", missing);
 sampleAX = (myControl)CTP.ContentControl;
 sampleAX.InsertTextClicked += new InsertTextEventHandler(sampleAX_InsertTextClicked);
 CTP.Visible = true;
}
Note Note

You can create custom task panes in any language that supports COM and allows you to create dynamic-linked library (DLL) files. For example, Microsoft Visual Basic® 6.0, Microsoft Visual Basic .NET, Microsoft Visual C++®, Microsoft Visual C++ .NET, and Microsoft Visual C#®. However, Microsoft Visual Basic for Applications (VBA) does not support creating custom task panes.

See also

Concepts

ICustomTaskPaneConsumer Object

Other resources

ICustomTaskPaneConsumer Object Members


IDocumentInspector Object (Office)

 Copy code hover
[image]

IDocumentInspector Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the interface through which the methods of a IDocumentInspector object are accessed.

Remarks

IDocumentInspector provides access to the GetInfo, Inspect, and Fix methods. The IDocumentInspector object is used with custom Document Inspector modules. This is in contrast to modules that are shipped with Microsoft Office.

Note Note

The IDocumentInspector object is for the exclusive use of custom Document Inspector module authors and cannot be used with Microsoft Visual Basic for Applications (VBA).

See also

Concepts

Object Model Reference

Other resources

IDocumentInspector Object Members


IDocumentInspector Members (Office)

 Copy code hover
[image]

IDocumentInspector Members (Office)
Send feedback

Published: July 09, 2012

Represents the interface through which the methods of a IDocumentInspector object are accessed.

Methods

Name | Description
Fix | Performs some action on specific information items or document properties by using a custom Document Inspector module.
GetInfo | Gets information about a custom Document Inspector module.
Inspect | Inspects a document for specific information items or document properties by using a custom Document Inspector module.


IDocumentInspector Methods (Office)

 Copy code hover
[image]

IDocumentInspector Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Fix | Performs some action on specific information items or document properties by using a custom Document Inspector module.
GetInfo | Gets information about a custom Document Inspector module.
Inspect | Inspects a document for specific information items or document properties by using a custom Document Inspector module.


IDocumentInspector.Fix Method (Office)

 Copy code hover
[image]

IDocumentInspector.Fix Method (Office)
See also Send feedback

Published: July 09, 2012

Performs some action on specific information items or document properties by using a custom Document Inspector module.

Syntax

expression .Fix(Doc, Hwnd, Status, Result)

expression An expression that returns a IDocumentInspector object.

Parameters

Name | Required/Optional | Data Type | Description
Doc | Required | Object | An object representing the container object.
Hwnd | Required | Long | Unique identifier of the active document window.
Status | Required | MsoDocInspectorStatus | An enumeration that indicates the status of the action.
Result | Required | String | Contains the results of the action.

Return Value

[HRESULT]

Remarks

MsoDocInspectorStatus members

Note Note

The IDocumentInspector object is for the exclusive use of custom Document Inspector module authors and cannot be used with Visual Basic for Applications (VBA).

See also

Concepts

IDocumentInspector Object

Other resources

IDocumentInspector Object Members


IDocumentInspector.GetInfo Method (Office)

 Copy code hover
[image]

IDocumentInspector.GetInfo Method (Office)
See also Send feedback

Published: July 09, 2012

Gets information about a custom Document Inspector module.

Syntax

expression .GetInfo(Name, Desc)

expression An expression that returns a IDocumentInspector object.

Parameters

Name | Required/Optional | Data Type | Description
Name | Required | String | Represents the name of the module.
Desc | Required | String | Represents the description of the module.

Return Value

[HRESULT]

Note Note

The IDocumentInspector object is for the exclusive use of custom Document Inspector module authors and cannot be used with Visual Basic for Applications (VBA).

See also

Concepts

IDocumentInspector Object

Other resources

IDocumentInspector Object Members


IDocumentInspector.Inspect Method (Office)

 Copy code hover
[image]

IDocumentInspector.Inspect Method (Office)
See also Send feedback

Published: July 09, 2012

Inspects a document for specific information items or document properties by using a custom Document Inspector module.

Syntax

expression .Inspect(Doc, Status, Result, Action)

expression An expression that returns a IDocumentInspector object.

Parameters

Name | Required/Optional | Data Type | Description
Doc | Required | Object | An object representing the container document.
Status | Required | MsoDocInspectorStatus | An enumeration that represents the results of the inspection.
Result | Required | String | Contains a list of the information items or document properties found in the document.
Action | Required | String | Indicates to the user what action to take based on the results of the inspection.

Return Value

[HRESULT]

Remarks

MsoDocInspectorStatus members

Note Note

The IDocumentInspector object is for the exclusive use of custom Document Inspector module authors and cannot be used with Visual Basic for Applications (VBA).

See also

Concepts

IDocumentInspector Object

Other resources

IDocumentInspector Object Members


IMsoContactCard Object (Office)

 Copy code hover
[image]

IMsoContactCard Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a Contact card.

Version Information

Version Added: Office 2010

Remarks

You cannot create a new instance of a ContactCard object programmatically. The ContactCard object is returned as an IRibbonControl.Context object when a Microsoft Office Fluent Ribbon callback procedure is triggered from the Contact Card context menu. You use the ContactCard object to determine additional information about the entity displayed in the Contact Card.

See also

Concepts

Object Model Reference

Other resources

IMsoContactCard Object Members


IMsoContactCard Members (Office)

 Copy code hover
[image]

IMsoContactCard Members (Office)
Send feedback

Published: July 09, 2012

Represents a Contact card.

Properties

Name | Description
Address | Represents the address in a Contact card. Read-only
AddressType | A MsoContactCardAddressType value that represents the address type for the ContactCard object. Read-only
Application | Gets an Application object that represents the container application for the IMsoContactCard object. Read-only
CardType | A MsoContactCardType value that represents the type of a Contact card. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the IMsoContactCard object was created. Read-only
Parent | Returns the calling object. Read-only


IMsoContactCard Properties (Office)

 Copy code hover
[image]

IMsoContactCard Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Address | Represents the address in a Contact card. Read-only
AddressType | A MsoContactCardAddressType value that represents the address type for the ContactCard object. Read-only
Application | Gets an Application object that represents the container application for the IMsoContactCard object. Read-only
CardType | A MsoContactCardType value that represents the type of a Contact card. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the IMsoContactCard object was created. Read-only
Parent | Returns the calling object. Read-only


IMsoContactCard.Address Property (Office)

 Copy code hover
[image]

IMsoContactCard.Address Property (Office)
See also Send feedback

Published: July 09, 2012

Represents the address in a Contact card. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Address

expression An expression that returns a IMsoContactCard object.

See also

Concepts

IMsoContactCard Object

Other resources

IMsoContactCard Object Members


IMsoContactCard.AddressType Property (Office)

 Copy code hover
[image]

IMsoContactCard.AddressType Property (Office)
See also Send feedback

Published: July 09, 2012

A MsoContactCardAddressType value that represents the address type for the ContactCard object. Read-only

Version Information

Version Added: Outlook 2010

Syntax

expression .AddressType

expression An expression that returns a IMsoContactCard object.

Remarks

The MsoContactCardAddressType enumeration consists of the following members:

Enumeration | Description
msoContactCardAddressTypeOutlook | Represents a unique identifier for an Outlook address.
msoContactCardAddressTypeSMTP | Represents a unique identifier for an SMTP address.
msoContactCardAddressTypeIM | Represents a unique identifier for an IM address.

See also

Concepts

IMsoContactCard Object

Other resources

IMsoContactCard Object Members


IMsoContactCard.Application Property (Office)

 Copy code hover
[image]

IMsoContactCard.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the IMsoContactCard object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a IMsoContactCard object.

See also

Concepts

IMsoContactCard Object

Other resources

IMsoContactCard Object Members


IMsoContactCard.CardType Property (Office)

 Copy code hover
[image]

IMsoContactCard.CardType Property (Office)
See also Send feedback

Published: July 09, 2012

A MsoContactCardType value that represents the type of a Contact card. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .CardType

expression An expression that returns a IMsoContactCard object.

Remarks

The MsoContactCardType enumeration consists of the following members:

Enumeration | Description
msoContactCardTypeEnterpriseContact | Represents a contact card for an Enterprise contact address.
msoContactCardTypePersonalContact | Represents a contact card for a personal contact address.
msoContactCardTypeUnknownContact | Represents a contact card for an unknown contact address.
msoContactCardTypeEnterpriseGroup | Represents a contact card for a an Enterprise distribution list address.
msoContactCardTypePersonalDistributionList | Represents a personal distribution list contact address.

See also

Concepts

IMsoContactCard Object

Other resources

IMsoContactCard Object Members


IMsoContactCard.Creator Property (Office)

 Copy code hover
[image]

IMsoContactCard.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the IMsoContactCard object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a IMsoContactCard object.

See also

Concepts

IMsoContactCard Object

Other resources

IMsoContactCard Object Members


IMsoContactCard.Parent Property (Office)

 Copy code hover
[image]

IMsoContactCard.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the calling object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Parent

expression An expression that returns a IMsoContactCard object.

See also

Concepts

IMsoContactCard Object

Other resources

IMsoContactCard Object Members


IRibbonControl Object (Office)

 Copy code hover
[image]

IRibbonControl Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the object passed into the callback procedure of a control in a ribbon or another user interface that can be customized by using Office Fluent ribbon extensibility.

Remarks

The IRibbonControl object contains the name (ID) of the control and the current Window object for the Ribbon UI control.

Example

The following example, written in C#, shows two procedures called from the onAction event procedure of a Button control and a ToggleButton control. In the first procedure, the IRibbonControl object representing the control is passed into the procedure and a message box is displayed indicating that the button was pressed along with the ID of the button. The second procedure is similar to the first with the addition of a Boolean parameter indicating that the button was pressed.

Copy code Copy code
public void ButtonOnAction(IRibbonControl control)
{
 MessageBox.Show("Button clicked: " + control.Id);
}

public void ToggleButtonOnAction(IRibbonControl control, bool pressed)
{
...if (pressed)
 MessageBox.Show("ToggleButton was switched on.");
 else
 MessageBox.Show("ToggleButton was switched off.");
}

See also

Concepts

Object Model Reference

Other resources

IRibbonControl Object Members


IRibbonControl Members (Office)

 Copy code hover
[image]

IRibbonControl Members (Office)
Send feedback

Published: July 09, 2012

Represents the object passed into the callback procedure of a control in a ribbon or another user interface that can be customized by using Office Fluent ribbon extensibility.

Properties

Name | Description
Context | Represents the active window containing the Ribbon user interface that triggers a callback procedure. Read-only.
Id | Gets the ID of the control specified in the Ribbon XML markup customization file. Read-only.
Tag | Used to store arbitrary strings and fetch them at runtime. Read-only


IRibbonControl Properties (Office)

 Copy code hover
[image]

IRibbonControl Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Context | Represents the active window containing the Ribbon user interface that triggers a callback procedure. Read-only.
Id | Gets the ID of the control specified in the Ribbon XML markup customization file. Read-only.
Tag | Used to store arbitrary strings and fetch them at runtime. Read-only


IRibbonControl.Context Property (Office)

 Copy code hover
[image]

IRibbonControl.Context Property (Office)
See also Send feedback

Published: July 09, 2012

Represents the active window containing the Ribbon user interface that triggers a callback procedure. Read-only.

Syntax

expression .Context

expression An expression that returns a IRibbonControl object.

Return Value

Object

See also

Concepts

IRibbonControl Object

Other resources

IRibbonControl Object Members


IRibbonControl.Id Property (Office)

 Copy code hover
[image]

IRibbonControl.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the ID of the control specified in the Ribbon XML markup customization file. Read-only.

Syntax

expression .Id

expression An expression that returns a IRibbonControl object.

Return Value

String

See also

Concepts

IRibbonControl Object

Other resources

IRibbonControl Object Members


IRibbonControl.Tag Property (Office)

 Copy code hover
[image]

IRibbonControl.Tag Property (Office)
See also Send feedback

Published: July 09, 2012

Used to store arbitrary strings and fetch them at runtime. Read-only

Syntax

expression .Tag

expression An expression that returns a IRibbonControl object.

Return Value

String

Remarks

Normally you can distinguish between controls in a Ribbon user interface XML customization file using the Id property. However, there are restrictions on what IDs can contain (no non-alphanumeric characters, and they must all be unique). The Tag property doesn't have these restrictions and so it can be used in the following situations, where ID doesn't work:

  • If you need to store a special string with your control such as a filename. For example: tag="C:\path\file.xlsm."

  • If you want multiple controls to be treated the same way by your callback procedures, but you don't want to maintain a list of all of their IDs (which must be unique). For example, you could have buttons on different tabs on the Ribbon, all with tag="blue", and then just check the Tag property instead of the ID property when perfroming some common action.

Example

In the XML used to customize the Ribbon user interface, you can set a tag as follows. When the MyFunction action is called, you can read the Tag property, which will be equal to "some string".

XML Copy code Copy code
<button id="mybutton" tag="some string" onAction="MyFunction"/>

See also

Concepts

IRibbonControl Object

Other resources

IRibbonControl Object Members


IRibbonExtensibility Object (Office)

 Copy code hover
[image]

IRibbonExtensibility Object (Office)
See also Send feedback

Published: July 09, 2012

The interface through which the Ribbon user interface (UI) communicates with a COM add-in to customize the UI.

Remarks

The IRibbonExtensibility interface has a single method, GetCustomUI.

Example

In the following example, written in C#, the IRibbonExtensibility interface is specified in the class definition. The procedure then implements the interfaces's only method, GetCustomUI. This method creates an instance of a SteamReader object that reads in the customized markup stored in an external XML file.

Copy code Copy code
public class Connect : Object, Extensibility.IDTExtensibility2, IRibbonExtensibility
...
public string GetCustomUI(string RibbonID)
{
 StreamReader customUIReader = new System.IO.StreamReader("C:\\RibbonXSampleCS\\customUI.xml");
 string customUIData = customUIReader.ReadToEnd();
 return customUIData;
}

See also

Concepts

Object Model Reference

Other resources

IRibbonExtensibility Object Members


IRibbonExtensibility Members (Office)

 Copy code hover
[image]

IRibbonExtensibility Members (Office)
Send feedback

Published: July 09, 2012

The interface through which the Ribbon user interface (UI) communicates with a COM add-in to customize the UI.

Methods

Name | Description
GetCustomUI | Loads the XML markup, either from an XML customization file or from XML markup embedded in the procedure, that customizes the Ribbon user interface.


IRibbonExtensibility Methods (Office)

 Copy code hover
[image]

IRibbonExtensibility Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
GetCustomUI | Loads the XML markup, either from an XML customization file or from XML markup embedded in the procedure, that customizes the Ribbon user interface.


IRibbonExtensibility.GetCustomUI Method (Office)

 Copy code hover
[image]

IRibbonExtensibility.GetCustomUI Method (Office)
See also Send feedback

Published: July 09, 2012

Loads the XML markup, either from an XML customization file or from XML markup embedded in the procedure, that customizes the Ribbon user interface.

Syntax

expression .GetCustomUI(RibbonID)

expression An expression that returns a IRibbonExtensibility object.

Parameters

Name | Required/Optional | Data Type | Description
RibbonID | Required | String | The ID for the RibbonX UI.

Return Value

String

Remarks

For Word, Excel, PowerPoint, and Access, there is only one ID for each application. Outlook uses ribbon extensibility to customize not only the ribbon in an inspector, but also the ribbon in an explorer, in various context menus, in contextual tabs in a ribbon, and in the Microsoft Office Backstage view. In each of these scenarios, the developer specifies the custom UI in an XML file that is loaded when Office calls GetCustomUI with a specific ribbon ID.

Example

In the following example, written in C#, the IRibbonExtensibility interface is specified in the class definition. The example then implements the interfaces's only method, GetCustomUI. The method creates an instance of a SteamReader object that reads in the customization markup in an external XML file.

Copy code Copy code
public class Connect : Object, Extensibility.IDTExtensibility2, IRibbonExtensibility
...
public string GetCustomUI(string RibbonID)
{
 StreamReader customUIReader = new System.IO.StreamReader("C:\\RibbonXSampleCS\\customUI.xml");
 string customUIData = customUIReader.ReadToEnd();
 return customUIData;
}

See also

Concepts

IRibbonExtensibility Object

Other resources

IRibbonExtensibility Object Members


IRibbonUI Object (Office)

 Copy code hover
[image]

IRibbonUI Object (Office)
See also Send feedback

Published: July 09, 2012

The object that is returned by the onLoad procedure specified on the customUI tag. The object contains methods for invalidating control properties and for refreshing the user interface.

Remarks

You can customize the Ribbon user interface (UI) by using callback procedures in COM add-ins. When the host application starts, the onLoad callback procedure is called. The callback procedure then returns a IRibbonUI object pointing to the user interface (UI). YOu can use that object to invoke the Invalidate, InvalidateControl, and Refresh methods.

Example

In the following example, starting the host application triggers the onLoad event procedure that then calls a procedure which creates a IRibbonUI object representing the Ribbon UI. Next, a callback procedure is defined that invalidates all of the cached controls and then refreshes the UI.

XML Copy code Copy code
<customUI … OnLoad="MyAddInInitialize" …>
VBA Copy code Copy code
Dim MyRibbon As IRibbonUI

Sub MyAddInInitialize(Ribbon As IRibbonUI)
 Set MyRibbon = Ribbon
End Sub

Sub myFunction()
 MyRibbon.Invalidate() ' Invalidates the caches of all of this add-in's controls
End Sub

See also

Concepts

Object Model Reference

Other resources

IRibbonUI Object Members


IRibbonUI Members (Office)

 Copy code hover
[image]

IRibbonUI Members (Office)
Send feedback

Published: July 09, 2012

The object that is returned by the onLoad procedure specified on the customUI tag. The object contains methods for invalidating control properties and for refreshing the user interface.

Methods

Name | Description
ActivateTab | Activates the specified custom tab.
ActivateTabMso | Activates the specified built-in tab.
ActivateTabQ | Activates the specified custom tab on the Microsoft Office Fluent Ribbon UI. Uses the fully qualified name of the tab which includes the ID and the namespace of the tab.
Invalidate | Invalidates the cached values for all of the controls of the Ribbon user interface.
InvalidateControl | Invalidates the cached value for a single control on the Ribbon user interface.
InvalidateControlMso | Used to invalidate a built-in control.


IRibbonUI Methods (Office)

 Copy code hover
[image]

IRibbonUI Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
ActivateTab | Activates the specified custom tab.
ActivateTabMso | Activates the specified built-in tab.
ActivateTabQ | Activates the specified custom tab on the Microsoft Office Fluent Ribbon UI. Uses the fully qualified name of the tab which includes the ID and the namespace of the tab.
Invalidate | Invalidates the cached values for all of the controls of the Ribbon user interface.
InvalidateControl | Invalidates the cached value for a single control on the Ribbon user interface.
InvalidateControlMso | Used to invalidate a built-in control.


IRibbonUI.ActivateTab Method (Office)

 Copy code hover
[image]

IRibbonUI.ActivateTab Method (Office)
See also Send feedback

Published: July 09, 2012

Activates the specified custom tab.

Version Information

Version Added: Office 2010

Syntax

expression .ActivateTab(ControlID)

expression An expression that returns a IRibbonUI object.

Parameters

Name | Required/Optional | Data Type | Description
ControlID | Required | String | Specifies the Id of the custom Ribbon tab to be activated.

Return Value

Nothing

Example

The following code makes the custom tab the active tab.

VBA Copy code Copy code
Public myRibbon As IRibbonUI

Sub tabActivate(ByVal control As IRibbonControl)
 myRibbon.ActivateTab (control.ID)
End Sub

See also

Concepts

IRibbonUI Object

Other resources

IRibbonUI Object Members


IRibbonUI.ActivateTabMso Method (Office)

 Copy code hover
[image]

IRibbonUI.ActivateTabMso Method (Office)
See also Send feedback

Published: July 09, 2012

Activates the specified built-in tab.

Version Information

Version Added: Office 2010

Syntax

expression .ActivateTabMso(ControlID)

expression An expression that returns a IRibbonUI object.

Parameters

Name | Required/Optional | Data Type | Description
ControlID | Required | String | Specifies the Id of the custom Ribbon tab to be activated.

Return Value

Nothing

Example

The following code make a built-in tab as specified by the control ID the active tab.

VBA Copy code Copy code
Public myRibbon As IRibbonUI

Sub tabActivate(ByVal control As IRibbonControl)
 myRibbon.ActivateTabMso (control.ID)
End Sub

See also

Concepts

IRibbonUI Object

Other resources

IRibbonUI Object Members


IRibbonUI.ActivateTabQ Method (Office)

 Copy code hover
[image]

IRibbonUI.ActivateTabQ Method (Office)
See also Send feedback

Published: July 09, 2012

Activates the specified custom tab on the Microsoft Office Fluent Ribbon UI. Uses the fully qualified name of the tab which includes the ID and the namespace of the tab.

Version Information

Version Added: Office 2010

Syntax

expression .ActivateTabQ(ControlID, Namespace)

expression An expression that returns a IRibbonUI object.

Parameters

Name | Required/Optional | Data Type | Description
ControlID | Required | String | Specifies the Id of the custom Ribbon tab to be activated.
Namespace | Required | String | Specifies the namespace of the tab element.

Return Value

Nothing

Example

The following code activates the qualified tab "test:MyTab". It assumes that you have defined the tab in the Ribbon definition file (customUI.xml) file as follows. The subroutine that follows is called from the onLoad attribute of the <customUI> element in the customUI.xml file.

  • xmlns:test="testnamespace"

  • <tab idQ="test:MyTab" >

VBA Copy code Copy code
Public myRibbon As IRibbonUI

Sub OnLoad(ByVal control As IRibbonControl)
 myRibbon.ActivateTabQ "MyTab", "testnamespace"
End Sub

See also

Concepts

IRibbonUI Object

Other resources

IRibbonUI Object Members


IRibbonUI.Invalidate Method (Office)

 Copy code hover
[image]

IRibbonUI.Invalidate Method (Office)
See also Send feedback

Published: July 09, 2012

Invalidates the cached values for all of the controls of the Ribbon user interface.

Syntax

expression .Invalidate

expression An expression that returns a IRibbonUI object.

Remarks

You can customize the Ribbon UI by using callback procedures in COM add-ins. For each of the callbacks the add-in implements, the responses are cached. For example, if an add-in writer implements the getImage callback procedure for a button, the function is called once, the image loads, and then if the image needs to be updated, the cached image is used instead of recalling the procedure. This process remains in-place until the add-in signals that the cached values are invalid by using the Invalidate method, at which time, the callback procedure is again called and the return response is cached. The add-in can then force an immediate update of the UI by calling the Refresh method.

Example

In the following example, starting the host application triggers the onLoad event procedure that then calls a procedure which creates an object representing the Ribbon UI. Next, a callback procedure is defined that invalidates all of the controls on the UI and then refreshes the UI.

XML Copy code Copy code
<customUI … OnLoad="MyAddinInitialize" …>
VBA Copy code Copy code
Dim MyRibbon As IRibbonUI

Sub MyAddInInitialize(Ribbon As IRibbonUI)
 Set MyRibbon = Ribbon
End Sub

Sub myFunction()
 MyRibbon.Invalidate() ' Invalidates the caches of all of this add-in's controls
End Sub

See also

Concepts

IRibbonUI Object

Other resources

IRibbonUI Object Members


IRibbonUI.InvalidateControl Method (Office)

 Copy code hover
[image]

IRibbonUI.InvalidateControl Method (Office)
See also Send feedback

Published: July 09, 2012

Invalidates the cached value for a single control on the Ribbon user interface.

Syntax

expression .InvalidateControl(bstrControlID)

expression An expression that returns a IRibbonUI object.

Parameters

Name | Required/Optional | Data Type | Description
bstrControlID | Required | String | Specifies the ID of the control that will be invalidated.

Remarks

You can customize the Ribbon UI by using callback procedures in COM add-ins. For each of the callbacks the add-in implements, the responses are cached. For example, if an add-in writer implements the getImage callback procedure for a button, the function is called once, the image loads, and then if the image needs to be updated, the cached image is used instead of recalling the procedure. This process remains in-place for the control until the add-in signals that the cached values are invalid by using the InvalidateControl method, at which time, the callback procedure is again called and the return response is cached.

Example

In the following example, starting the host application triggers the onLoad event procedure that then calls a procedure which creates an object representing the Ribbon UI. Next, a callback procedure is defined that invalidates a control on the UI and then refreshes the UI.

XML Copy code Copy code
<customUI … OnLoad="MyAddInInitialize" …>
VBA Copy code Copy code
Dim MyRibbon As IRibbonUI

Sub MyAddInInitialize(Ribbon As IRibbonUI)
 Set MyRibbon = Ribbon
End Sub

Sub myFunction()
 MyRibbon.InvalidateControl("control1") ' Invalidates the cache of a single control
End Sub

See also

Concepts

IRibbonUI Object

Other resources

IRibbonUI Object Members


IRibbonUI.InvalidateControlMso Method (Office)

 Copy code hover
[image]

IRibbonUI.InvalidateControlMso Method (Office)
See also Send feedback

Published: July 09, 2012

Used to invalidate a built-in control.

Version Information

Version Added: Office 2010

Syntax

expression .InvalidateControlMso(ControlID)

expression An expression that returns a IRibbonUI object.

Parameters

Name | Required/Optional | Data Type | Description
ControlID | Required | String |

Return Value

Nothing

Remarks

Invalidating a control repaints the screen and causes any callback procedures associated with that control to execute.

Example

XML Copy code Copy code
<customUI … OnLoad="MyAddInInitialize" …>
VBA Copy code Copy code
Sub MyAddInInitialize(Ribbon As IRibbonUI)
 Set MyRibbon = Ribbon
End Sub

Sub myFunction()
 MyRibbon.InvalidateControlMso("TabInsert") ' Invalidates the Insert control
End Sub

See also

Concepts

IRibbonUI Object

Other resources

IRibbonUI Object Members


LanguageSettings Object (Office)

 Copy code hover
[image]

LanguageSettings Object (Office)
See also Send feedback

Published: July 09, 2012

Returns information about the language settings in a Microsoft Office application.

Remarks

Use Application.LanguageSettings.LanguageID(MsoAppLanguageID ), where MsoAppLanguageID is a constant used to return locale identifier (LCID) information to the specified application.

Example

The following example returns the install language, user interface language, and Help language LCIDs in a message box.

Copy code Copy code
MsgBox "The following locale IDs are registered " & _
 "for this application: Install Language - " & _
 Application.LanguageSettings.LanguageID(msoLanguageIDInstall) & _
 " User Interface Language - " & _
 Application.LanguageSettings.LanguageID(msoLanguageIDUI) & _
 " Help Language - " & _
 Application.LanguageSettings.LanguageID(msoLanguageIDHelp)

Use Application.LanguageSettings.LanguagePreferredForEditing to determine which LCIDs are registered as preferred editing languages for the application, as in the following example.

Copy code Copy code
If Application.LanguageSettings. _
 LanguagePreferredForEditing(msoLanguageIDEnglishUS) Then
 MsgBox "U.S. English is one of the chosen editing languagess."
End If

See also

Concepts

Object Model Reference

Other resources

LanguageSettings Object Members


LanguageSettings Members (Office)

 Copy code hover
[image]

LanguageSettings Members (Office)
Send feedback

Published: July 09, 2012

Returns information about the language settings in a Microsoft Office application.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the LanguageSettings object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the LanguageSettings object was created. Read-only.
LanguageID | Gets a MsoAppLanguageID constant representing the locale identifier (LCID) for the install language, the user interface language, or the Help language. Read-only.
LanguagePreferredForEditing | Gets True if the value for the MsoLanguageID constant has been identified in the Windows registry as a preferred language for editing. Read-only.
Parent | Gets the Parent object for the ODSOFilter object. Read-only.


LanguageSettings Properties (Office)

 Copy code hover
[image]

LanguageSettings Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the LanguageSettings object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the LanguageSettings object was created. Read-only.
LanguageID | Gets a MsoAppLanguageID constant representing the locale identifier (LCID) for the install language, the user interface language, or the Help language. Read-only.
LanguagePreferredForEditing | Gets True if the value for the MsoLanguageID constant has been identified in the Windows registry as a preferred language for editing. Read-only.
Parent | Gets the Parent object for the ODSOFilter object. Read-only.


LanguageSettings.Application Property (Office)

 Copy code hover
[image]

LanguageSettings.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the LanguageSettings object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a LanguageSettings object.

Return Value

Object

See also

Concepts

LanguageSettings Object

Other resources

LanguageSettings Object Members


LanguageSettings.Creator Property (Office)

 Copy code hover
[image]

LanguageSettings.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the LanguageSettings object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a LanguageSettings object.

Return Value

Long

See also

Concepts

LanguageSettings Object

Other resources

LanguageSettings Object Members


LanguageSettings.LanguageID Property (Office)

 Copy code hover
[image]

LanguageSettings.LanguageID Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a MsoAppLanguageID constant representing the locale identifier (LCID) for the install language, the user interface language, or the Help language. Read-only.

Syntax

expression .LanguageID(Id)

expression A variable that represents a LanguageSettings object.

Parameters

Name | Required/Optional | Data Type | Description
Id | Required | MsoAppLanguageID | Returns one of the MsoAppLanguageID enumerations.

Example

This Microsoft Excel example checks the LanguageID property settings for the user interface and execution mode to verify that they are set to the same LCID. The example returns an error if there is a discrepancy.

Copy code Copy code
If Application.LanguageSettings.LanguageID(msoLanguageIDExeMode) _
 > Application.LanguageSettings.LanguageID(msoLanguageIDUI) _
 Then MsgBox "The user interface language and execution " & _
 "mode are different."

See also

Concepts

LanguageSettings Object

Other resources

LanguageSettings Object Members


LanguageSettings.LanguagePreferredForEditing Property (Office)

 Copy code hover
[image]

LanguageSettings.LanguagePreferredForEditing Property (Office)
See also Send feedback

Published: July 09, 2012

Gets True if the value for the MsoLanguageID constant has been identified in the Windows registry as a preferred language for editing. Read-only.

Syntax

expression .LanguagePreferredForEditing(lid)

expression A variable that represents a LanguageSettings object.

Parameters

Name | Required/Optional | Data Type | Description
lid | Required | MsoLanguageID | Returns one of the MsoLanguageID enumerations.

Remarks

You must test all valid msoLanguageID values to enumerate the set of preferred languages.

Example

This example displays a message if U.S. English is a preferred editing language.

Copy code Copy code
If Application.LanguageSettings. _
 LanguagePreferredForEditing(msoLanguageIDEnglishUS) Then
 MsgBox "One of the preferred editing languages is US English."
End If

See also

Concepts

LanguageSettings Object

Other resources

LanguageSettings Object Members


LanguageSettings.Parent Property (Office)

 Copy code hover
[image]

LanguageSettings.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ODSOFilter object. Read-only.

Syntax

expression .Parent

expression A variable that represents a LanguageSettings object.

Return Value

Object

See also

Concepts

LanguageSettings Object

Other resources

LanguageSettings Object Members


MetaProperties Object (Office)

 Copy code hover
[image]

MetaProperties Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of properties describing the metadata stored in a document.

Example

In the following example, a MetaProperties object is passed to a validation function. The function then validates the value of a single property represented by its index and returns the result.

VBA Copy code Copy code
Function ValidateMetaProperty(ByVal metaProps As MetaProperties) As String
Dim result As String

result = metaProps(1).Validate
ValidateMetaProperty = result
End Function

See also

Concepts

Object Model Reference

Other resources

MetaProperties Object Members


MetaProperties Members (Office)

 Copy code hover
[image]

MetaProperties Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of properties describing the metadata stored in a document.

Methods

Name | Description
GetItemByInternalName | Gets a property's value specifying its name as opposed to its index value.
Validate | Validates all of the properties in a MetaProperties collection object according to a schema.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the MetaProperties object. Read-only.
Count | Gets a Long indicating the number of items in the MetaProperties collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the MetaProperties object was created. Read-only.
Item | Gets a MetaProperty object from the MetaProperties collection. Read-only.
Parent | Gets the Parent object for the MetaProperties object. Read-only.
SchemaXml | Gets the schema XML for the MetaProperties object. Read-only.


MetaProperties Properties (Office)

 Copy code hover
[image]

MetaProperties Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the MetaProperties object. Read-only.
Count | Gets a Long indicating the number of items in the MetaProperties collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the MetaProperties object was created. Read-only.
Item | Gets a MetaProperty object from the MetaProperties collection. Read-only.
Parent | Gets the Parent object for the MetaProperties object. Read-only.
SchemaXml | Gets the schema XML for the MetaProperties object. Read-only.


MetaProperties.Application Property (Office)

 Copy code hover
[image]

MetaProperties.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the MetaProperties object. Read-only.

Syntax

expression .Application

expression An expression that returns a MetaProperties object.

Return Value

Object

See also

Concepts

MetaProperties Object

Other resources

MetaProperties Object Members


MetaProperties.Count Property (Office)

 Copy code hover
[image]

MetaProperties.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the MetaProperties collection. Read-only.

Syntax

expression .Count

expression An expression that returns a MetaProperties object.

Return Value

Long

See also

Concepts

MetaProperties Object

Other resources

MetaProperties Object Members


MetaProperties.Creator Property (Office)

 Copy code hover
[image]

MetaProperties.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the MetaProperties object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a MetaProperties object.

Return Value

Long

See also

Concepts

MetaProperties Object

Other resources

MetaProperties Object Members


MetaProperties.Item Property (Office)

 Copy code hover
[image]

MetaProperties.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a MetaProperty object from the MetaProperties collection. Read-only.

Syntax

expression .Item(Index)

expression An expression that returns a MetaProperties object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | The name or index number of the MetaProperty object to be returned.

Return Value

MetaProperty

See also

Concepts

MetaProperties Object

Other resources

MetaProperties Object Members


MetaProperties.Parent Property (Office)

 Copy code hover
[image]

MetaProperties.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the MetaProperties object. Read-only.

Syntax

expression .Parent

expression An expression that returns a MetaProperties object.

Return Value

Object

See also

Concepts

MetaProperties Object

Other resources

MetaProperties Object Members


MetaProperties.SchemaXml Property (Office)

 Copy code hover
[image]

MetaProperties.SchemaXml Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the schema XML for the MetaProperties object. Read-only.

Syntax

expression .SchemaXml

expression An expression that returns a MetaProperties object.

Return Value

String

Remarks

This property is used to return information representing various metadata properties of a document such as type information, restrictions, and so forth.

See also

Concepts

MetaProperties Object

Other resources

MetaProperties Object Members


MetaProperties Methods (Office)

 Copy code hover
[image]

MetaProperties Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
GetItemByInternalName | Gets a property's value specifying its name as opposed to its index value.
Validate | Validates all of the properties in a MetaProperties collection object according to a schema.


MetaProperties.GetItemByInternalName Method (Office)

 Copy code hover
[image]

MetaProperties.GetItemByInternalName Method (Office)
See also Send feedback

Published: July 09, 2012

Gets a property's value specifying its name as opposed to its index value.

Syntax

expression .GetItemByInternalName(InternalName)

expression An expression that returns a MetaProperty object.

Parameters

Name | Required/Optional | Data Type | Description
InternalName | Required | String | Contains the name of the property.

Return Value

MetaProperty

Remarks

Metadata is information about a document that can be used to identify particular documents, search document content, build rich content dynamically, and other similar operations without the need to open the document. Metadata can be stored in a document and as properties on a Microsoft SharePoint Foundation server.

Example

In the following example, a MetaProperties object is passed to a validation function. The function then retrieves the value of one of its properties and assigns it to a MetaProperty object. Finally, the property is validated and the results are returned.

VBA Copy code Copy code
Function ValidateMetaProperty(ByVal objMetaProperty As MetaProperty) As String
Dim objMetaProperty As MetaProperty
Dim result As String

objMetaProperty = objMetaProperty.GetItemByInternalName("type")
result = objMetaProperty.Validate

ValidateMetaProperty = result
End Function

See also

Concepts

MetaProperties Object

Other resources

MetaProperties Object Members


MetaProperties.Validate Method (Office)

 Copy code hover
[image]

MetaProperties.Validate Method (Office)
See also Send feedback

Published: July 09, 2012

Validates all of the properties in a MetaProperties collection object according to a schema.

Syntax

expression .Validate

expression An expression that returns a MetaProperties object.

Return Value

String

Remarks

If any of the properties is invalid, the test fails and an error message is returned. The schema used for validation is stored as part of the document's Microsoft SharePoint Foundation profile.

Example

In the following example, a MetaProperties object is passed to a validation function. The function then validates all of the properties of the object and returns the result.

VBA Copy code Copy code
Function ValidateMetaProperties(ByVal metaProps As MetaProperties) As String
Dim result As String

result = metaProps.Validate
ValidateMetaProperties = result
End Function

See also

Concepts

MetaProperties Object

Other resources

MetaProperties Object Members


MetaProperty Object (Office)

 Copy code hover
[image]

MetaProperty Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a single property in a collection of properties describing the metadata stored in a document.

Example

In the following example, a MetaProperties object is passed to a validation function. The function then validates the value of a single property represented by its index and returns the result.

VBA Copy code Copy code
Function ValidateMetaProperty(ByVal metaProps As MetaProperties) As String
Dim result As String

result = metaProps(1).Validate
ValidateMetaProperty = result
End Function

See also

Concepts

Object Model Reference

Other resources

MetaProperty Object Members


MetaProperty Members (Office)

 Copy code hover
[image]

MetaProperty Members (Office)
Send feedback

Published: July 09, 2012

Represents a single property in a collection of properties describing the metadata stored in a document.

Methods

Name | Description
Validate | Validates a MetaProperty object representing a single property value according to a schema.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the MetaProperty object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the MetaProperty object was created. Read-only.
Id | Gets the ID of the MetaProperty object. Read-only.
IsReadOnly | Gets a Boolean value that specifies whether the meta property is read-only. Read-only.
IsRequired | Gets a Boolean value that specifies whether the meta property is required. Read-only.
Name | Gets the name of the MetaProperty object. Read-only.
Parent | Gets the Parent object for the MetaProperty object. Read-only.
Type | Gets the data type of a MetaProperty object. Read-only.
Value | Gets or sets the value of the MetaProperty object. Read/write.


MetaProperty Properties (Office)

 Copy code hover
[image]

MetaProperty Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the MetaProperty object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the MetaProperty object was created. Read-only.
Id | Gets the ID of the MetaProperty object. Read-only.
IsReadOnly | Gets a Boolean value that specifies whether the meta property is read-only. Read-only.
IsRequired | Gets a Boolean value that specifies whether the meta property is required. Read-only.
Name | Gets the name of the MetaProperty object. Read-only.
Parent | Gets the Parent object for the MetaProperty object. Read-only.
Type | Gets the data type of a MetaProperty object. Read-only.
Value | Gets or sets the value of the MetaProperty object. Read/write.


MetaProperty.Application Property (Office)

 Copy code hover
[image]

MetaProperty.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the MetaProperty object. Read-only.

Syntax

expression .Application

expression An expression that returns a MetaProperty object.

Return Value

Object

See also

Concepts

MetaProperty Object

Other resources

MetaProperty Object Members


MetaProperty.Creator Property (Office)

 Copy code hover
[image]

MetaProperty.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the MetaProperty object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a MetaProperty object.

Return Value

Long

See also

Concepts

MetaProperty Object

Other resources

MetaProperty Object Members


MetaProperty.Id Property (Office)

 Copy code hover
[image]

MetaProperty.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the ID of the MetaProperty object. Read-only.

Syntax

expression .Id

expression An expression that returns a MetaProperty object.

Return Value

String

See also

Concepts

MetaProperty Object

Other resources

MetaProperty Object Members


MetaProperty.IsReadOnly Property (Office)

 Copy code hover
[image]

MetaProperty.IsReadOnly Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value that specifies whether the meta property is read-only. Read-only.

Syntax

expression .IsReadOnly

expression An expression that returns a MetaProperty object.

Return Value

Boolean

See also

Concepts

MetaProperty Object

Other resources

MetaProperty Object Members


MetaProperty.IsRequired Property (Office)

 Copy code hover
[image]

MetaProperty.IsRequired Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value that specifies whether the meta property is required. Read-only.

Syntax

expression .IsRequired

expression An expression that returns a MetaProperty object.

Return Value

Boolean

See also

Concepts

MetaProperty Object

Other resources

MetaProperty Object Members


MetaProperty.Name Property (Office)

 Copy code hover
[image]

MetaProperty.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the MetaProperty object. Read-only.

Syntax

expression .Name

expression An expression that returns a MetaProperty object.

Return Value

String

See also

Concepts

MetaProperty Object

Other resources

MetaProperty Object Members


MetaProperty.Parent Property (Office)

 Copy code hover
[image]

MetaProperty.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the MetaProperty object. Read-only.

Syntax

expression .Parent

expression An expression that returns a MetaProperty object.

Return Value

Object

See also

Concepts

MetaProperty Object

Other resources

MetaProperty Object Members


MetaProperty.Type Property (Office)

 Copy code hover
[image]

MetaProperty.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the data type of a MetaProperty object. Read-only.

Syntax

expression .Type

expression An expression that returns a MetaProperty object.

Return Value

MsoMetaPropertyType

See also

Concepts

MetaProperty Object

Other resources

MetaProperty Object Members


MetaProperty.Value Property (Office)

 Copy code hover
[image]

MetaProperty.Value Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the value of the MetaProperty object. Read/write.

Syntax

expression .Value

expression An expression that returns a MetaProperty object.

Return Value

Variant

See also

Concepts

MetaProperty Object

Other resources

MetaProperty Object Members


MetaProperty Methods (Office)

 Copy code hover
[image]

MetaProperty Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Validate | Validates a MetaProperty object representing a single property value according to a schema.


MetaProperty.Validate Method (Office)

 Copy code hover
[image]

MetaProperty.Validate Method (Office)
See also Send feedback

Published: July 09, 2012

Validates a MetaProperty object representing a single property value according to a schema.

Syntax

expression .Validate

expression An expression that returns a MetaProperty object.

Return Value

String

Remarks

If the property is invalid, the test fails and an error message is returned. The schema used for validation is stored as part of the document's Microsoft SharePoint Foundation profile.

Example

In the following example, a MetaProperties object is passed to a validation function. The function then validates the value of a single property represented by its index and returns the result.

VBA Copy code Copy code
Function ValidateMetaProperty(ByVal metaProps As MetaProperties) As String
Dim result As String

result = metaProps(1).Validate
ValidateMetaProperty = result
End Function

See also

Concepts

MetaProperty Object

Other resources

MetaProperty Object Members


MsoEnvelope Object (Office)

 Copy code hover
[image]

MsoEnvelope Object (Office)
See also Send feedback

Published: July 09, 2012

Provides access to functionality that lets you send documents as e-mail messages directly from Microsoft Office applications.

Remarks

Use the MailEnvelope property of the Document object, Chart object or Worksheet object (depending on the application you are using) to return a MsoEnvelope object.

Example

The following example sends the active Microsoft Word document as an e-mail message to the e-mail address that you pass to the subroutine.

Copy code Copy code
Sub SendMail(ByVal strRecipient As String)

 'Use a With...End With block to reference the MsoEnvelope object.
 With Application.ActiveDocument.MailEnvelope

 'Add some introductory text before the body of the e-mail.
 .Introduction = "Please read this and send me your comments."

 'Return a Microsoft Outlook MailItem object that
 'you can use to send the document.
 With .Item

 'All of the mail item settings are saved with the document.
 'When you add a recipient to the Recipients collection
 'or change other properties, these settings persist.
 .Recipients.Add strRecipient
 .Subject = "Here is the document."

 'The body of this message will be
 'the content of the active document.
 .Send
 End With
 End With
End Sub

See also

Concepts

Object Model Reference

Other resources

MsoEnvelope Object Members


MsoEnvelope Members (Office)

 Copy code hover
[image]

MsoEnvelope Members (Office)
Send feedback

Published: July 09, 2012

Provides access to functionality that lets you send documents as e-mail messages directly from Microsoft Office applications.

Events

Name | Description
EnvelopeHide | Occurs when the user interface (UI) that corresponds to the MsoEnvelope object is hidden.
EnvelopeShow | Occurs when the user interface (UI) that corresponds to the MsoEnvelope object is displayed.

Properties

Name | Description
CommandBars | Gets a CommandBars collection. Read-only.
Introduction | Sets or gets the introductory text that is included with a document that is sent using the MsoEnvelope object. The introductory text is included at the top of the document in the e-mail. Read/write.
Item | Gets a MailItem object that can be used to send the document as an e-mail. Read-only.
Parent | Gets the Parent object for the MsoEnvelope object. Read-only.


MsoEnvelope Properties (Office)

 Copy code hover
[image]

MsoEnvelope Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
CommandBars | Gets a CommandBars collection. Read-only.
Introduction | Sets or gets the introductory text that is included with a document that is sent using the MsoEnvelope object. The introductory text is included at the top of the document in the e-mail. Read/write.
Item | Gets a MailItem object that can be used to send the document as an e-mail. Read-only.
Parent | Gets the Parent object for the MsoEnvelope object. Read-only.


MsoEnvelope.CommandBars Property (Office)

 Copy code hover
[image]

MsoEnvelope.CommandBars Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a CommandBars collection. Read-only.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Syntax

expression .CommandBars

expression A variable that represents a MsoEnvelope object.

Example

The following example return the CommandBars collection from the MsoEnvelope object in Microsoft Word.

Copy code Copy code
Dim cbars As CommandBars
Set cbars = Application.ActiveDocument.MailEnvelope.Commandbars

See also

Concepts

MsoEnvelope Object

Other resources

MsoEnvelope Object Members


MsoEnvelope.Introduction Property (Office)

 Copy code hover
[image]

MsoEnvelope.Introduction Property (Office)
See also Send feedback

Published: July 09, 2012

Sets or gets the introductory text that is included with a document that is sent using the MsoEnvelope object. The introductory text is included at the top of the document in the e-mail. Read/write.

Syntax

expression .Introduction

expression A variable that represents a MsoEnvelope object.

Example

The following example sends the active Microsoft Word document as an e-mail to the e-mail address that you pass to the subroutine.

Copy code Copy code
Sub SendMail(ByVal strRecipient As String)

 'Use a With...End With block to reference the MsoEnvelope object.
 With Application.ActiveDocument.MailEnvelope

 'Add some introductory text before the body of the e-mail.
 .Introduction = "Please read this and send me your comments."

 'Return a MailItem object that you can use to send the document.
 With .Item

 'All of the mail item settings are saved with the document.
 'When you add a recipient to the Recipients collection
 'or change other properties these settings will persist.

 .Recipients.Add strRecipient
 .Subject = "Here is the document."

 'The body of this message will be
 'the content of the active document.
 .Send
 End With
 End With
End Sub

See also

Concepts

MsoEnvelope Object

Other resources

MsoEnvelope Object Members


MsoEnvelope.Item Property (Office)

 Copy code hover
[image]

MsoEnvelope.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a MailItem object that can be used to send the document as an e-mail. Read-only.

Syntax

expression .Item

expression Required. A variable that represents a MsoEnvelope object.

Example

The following example sends the active Microsoft Word document as an e-mail to the e-mail address that you pass to the subroutine.

VBA Copy code Copy code
Sub SendMail(ByVal strRecipient As String)

 'Use a With...End With block to reference the msoEnvelope object.
 With Application.ActiveDocument.MailEnvelope

 'Add some introductory text before the body of the e-mail message.
 .Introduction = "Please read this and send me your comments."

 'Return a MailItem object that you can use to send the document.
 With .Item

 'All of the mail item settings are saved with the document.
 'When you add a recipient to the Recipients collection
 'or change other properties these settings will persist.

 .Recipients.Add strRecipient
 .Subject = "Here is the document."

 'The body of this message will be
 'the content of the active document.
 .Send
 End With
 End With
End Sub

See also

Concepts

MsoEnvelope Object

Other resources

MsoEnvelope Object Members


MsoEnvelope.Parent Property (Office)

 Copy code hover
[image]

MsoEnvelope.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the MsoEnvelope object. Read-only.

Syntax

expression .Parent

expression A variable that represents a MsoEnvelope object.

Return Value

Object

See also

Concepts

MsoEnvelope Object

Other resources

MsoEnvelope Object Members


MsoEnvelope Events (Office)

 Copy code hover
[image]

MsoEnvelope Events (Office)
Send feedback

Published: July 09, 2012

This object has the following events:

Events

Name | Description
EnvelopeHide | Occurs when the user interface (UI) that corresponds to the MsoEnvelope object is hidden.
EnvelopeShow | Occurs when the user interface (UI) that corresponds to the MsoEnvelope object is displayed.


MsoEnvelope.EnvelopeHide Event (Office)

 Copy code hover
[image]

MsoEnvelope.EnvelopeHide Event (Office)
See also Send feedback

Published: July 09, 2012

Occurs when the user interface (UI) that corresponds to the MsoEnvelope object is hidden.

Syntax

expression .EnvelopeHide

expression An expression that returns a MsoEnvelope object.

Remarks

The MsoEnvelope object provides access to functionality that lets you send documents as e-mail messages directly from Microsoft Office applications.

Example

The following example sets up event-handling routines for the MsoEnvelope object.

VBA Copy code Copy code
Public WithEvents env As MsoEnvelope

Private Sub Class_Initialize()
 Set env = Application.ActiveDocument.MailEnvelope
End Sub

Private Sub env_EnvelopeShow()
 MsgBox "The MsoEnvelope UI is showing."
End Sub

Private Sub env_EnvelopeHide()
 MsgBox "The MsoEnvelope UI is hidden."
End Sub

See also

Concepts

MsoEnvelope Object

Other resources

MsoEnvelope Object Members


MsoEnvelope.EnvelopeShow Event (Office)

 Copy code hover
[image]

MsoEnvelope.EnvelopeShow Event (Office)
See also Send feedback

Published: July 09, 2012

Occurs when the user interface (UI) that corresponds to the MsoEnvelope object is displayed.

Syntax

expression .EnvelopeShow

expression An expression that returns a MsoEnvelope object.

Remarks

The MsoEnvelope object provides access to functionality that lets you send documents as e-mail messages directly from Microsoft Office applications.

Example

The following example sets up event-handling routines for the MsoEnvelope object.

VBA Copy code Copy code
Public WithEvents env As MsoEnvelope

Private Sub Class_Initialize()
 Set env = Application.ActiveDocument.MailEnvelope
End Sub

Private Sub env_EnvelopeShow()
 MsgBox "The MsoEnvelope UI is showing."
End Sub

Private Sub env_EnvelopeHide()
 MsgBox "The MsoEnvelope UI is hidden."
End Sub

See also

Concepts

MsoEnvelope Object

Other resources

MsoEnvelope Object Members


NewFile Object (Office)

 Copy code hover
[image]

NewFile Object (Office)
See also Send feedback

Published: July 09, 2012

Represents items listed on the New Item task pane available in several Microsoft Office applications.

Note Note

The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface. For more information, search Help for the keyword "ribbon."

Remarks

The following table shows the property to use to access the NewFile object in each of the applications.

Example

Use the Add method to add a new item to the New Item task pane. The following example adds an item to Word's New Document task pane.

Copy code Copy code
Sub AddNewDocToTaskPane()
    Application.NewDocument.Add FileName:="C:\NewDocument.doc", _
        Section:=msoNew, DisplayName:="New Document"
    CommandBars("Task Pane").Visible = True
End Sub

Use the Remove method to remove an item from the New Item task pane. The following example removes the document added in the above example from Word's New Document task pane.

Copy code Copy code
Sub RemoveDocFromTaskPane()
    Application.NewDocument.Remove FileName:="C:\NewDocument.doc", _
        Section:=msoNew, DisplayName:="New Document"
    CommandBars("Task Pane").Visible = True
End Sub
Note Note

Note Note

The examples below are for Word, but you can change the NewDocument property for any of the properties listed above and use the code in the corresponding application.

See also

Concepts

Object Model Reference

Other resources

NewFile Object Members


NewFile Members (Office)

 Copy code hover
[image]

NewFile Members (Office)
Send feedback

Published: July 09, 2012

Represents items listed on the New Item task pane available in several Microsoft Office applications.

Methods

Name | Description
Add | Adds a new item to the New Item task pane. Returns a Boolean value to indicate whether the operation was successful.
Remove | Removes an item from the New Item task pane. Returns a Boolean value to indicate whether the operation was successful.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the NewFile object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the NewFile object was created. Read-only.


NewFile Properties (Office)

 Copy code hover
[image]

NewFile Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the NewFile object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the NewFile object was created. Read-only.


NewFile.Application Property (Office)

 Copy code hover
[image]

NewFile.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the NewFile object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a NewFile object.

Return Value

Object

See also

Concepts

NewFile Object

Other resources

NewFile Object Members


NewFile.Creator Property (Office)

 Copy code hover
[image]

NewFile.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the NewFile object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a NewFile object.

Return Value

Long

See also

Concepts

NewFile Object

Other resources

NewFile Object Members


NewFile Methods (Office)

 Copy code hover
[image]

NewFile Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a new item to the New Item task pane. Returns a Boolean value to indicate whether the operation was successful.
Remove | Removes an item from the New Item task pane. Returns a Boolean value to indicate whether the operation was successful.


NewFile.Add Method (Office)

 Copy code hover
[image]

NewFile.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a new item to the New Item task pane. Returns a Boolean value to indicate whether the operation was successful.

Syntax

expression .Add(FileName, Section, DisplayName, Action)

expression Required. A variable that represents a NewFile object.

Parameters

Name | Required/Optional | Data Type | Description
FileName | Required | String | The name of the file to add to the list of files on the task pane.
Section | Optional | Variant | The section to which to add the file. Can be any msoFileNew constant.
DisplayName | Optional | Variant | The text to display in the task pane.
Action | Optional | Variant | The action to take when a user clicks the item. Can be any msoFileNew constant.

See also

Concepts

NewFile Object

Other resources

NewFile Object Members


NewFile.Remove Method (Office)

 Copy code hover
[image]

NewFile.Remove Method (Office)
See also Send feedback

Published: July 09, 2012

Removes an item from the New Item task pane. Returns a Boolean value to indicate whether the operation was successful.

Syntax

expression .Remove(FileName, Section, DisplayName, Action)

expression Required. A variable that represents a NewFile object.

Parameters

Name | Required/Optional | Data Type | Description
FileName | Required | String | The name of the file reference.
Section | Optional | Variant | The section of the task pane where the file reference exists. Can be any msoFileNew constant.
DisplayName | Optional | Variant | The display text of the file reference.

Remarks

The arguments supplied to the Remove method must match the arguments that were supplied to the Add method of the NewFile object, or the Remove method will fail. For example, if the Action argument was supplied when the NewFile object was added, then the same Action argument must be supplied to remove the NewFile object, or the Remove method will fail.

See also

Concepts

NewFile Object

Other resources

NewFile Object Members


ODSOColumn Object (Office)

 Copy code hover
[image]

ODSOColumn Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a field in a data source. The ODSOColumn object is a member of the ODSOColumns collection.

Remarks

The ODSOColumns collection includes all the data fields in a mail merge data source (for example, Name, Address, and City).

You cannot add fields to the ODSOColumns collection. All data fields in a data source are automatically included in the ODSOColumns collection.

Use Columns (index), where index is the data field name or index number, to return a single ODSOColumn object. The index number represents the position of the data field in the mail merge data source.

Example

This example retrieves the name and value of the first field of the first record in the data source attached to the active publication.

Copy code Copy code
Sub GetDataFromSource()

 Dim appOffice As OfficeDataSourceObject

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Columns
 MsgBox "Field Name: " & .Item(1).Name & vbLf & _
 "Value: " & .Item(1).Value
 End With
End Sub

See also

Concepts

Object Model Reference

Other resources

ODSOColumn Object Members


ODSOColumn Members (Office)

 Copy code hover
[image]

ODSOColumn Members (Office)
Send feedback

Published: July 09, 2012

Represents a field in a data source. The ODSOColumn object is a member of the ODSOColumns collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ODSOColumn object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ODSOColumn object was created. Read-only.
Index | Gets a Long representing the index number for an ODSOColumn object in the collection. Read-only.
Name | Gets the name of a data field in a mail merge data source. Read-only.
Parent | Gets the Parent object for the ODSOColumn object. Read-only.
Value | Gets the value of a data field in a mail merge data source. Read-only.


ODSOColumn Properties (Office)

 Copy code hover
[image]

ODSOColumn Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ODSOColumn object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ODSOColumn object was created. Read-only.
Index | Gets a Long representing the index number for an ODSOColumn object in the collection. Read-only.
Name | Gets the name of a data field in a mail merge data source. Read-only.
Parent | Gets the Parent object for the ODSOColumn object. Read-only.
Value | Gets the value of a data field in a mail merge data source. Read-only.


ODSOColumn.Application Property (Office)

 Copy code hover
[image]

ODSOColumn.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ODSOColumn object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents an ODSOColumn object.

Return Value

Object

See also

Concepts

ODSOColumn Object

Other resources

ODSOColumn Object Members


ODSOColumn.Creator Property (Office)

 Copy code hover
[image]

ODSOColumn.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ODSOColumn object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents an ODSOColumn object.

Return Value

Long

See also

Concepts

ODSOColumn Object

Other resources

ODSOColumn Object Members


ODSOColumn.Index Property (Office)

 Copy code hover
[image]

ODSOColumn.Index Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long representing the index number for an ODSOColumn object in the collection. Read-only.

Syntax

expression .Index

expression A variable that represents an ODSOColumn object.

Return Value

Long

See also

Concepts

ODSOColumn Object

Other resources

ODSOColumn Object Members


ODSOColumn.Name Property (Office)

 Copy code hover
[image]

ODSOColumn.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of a data field in a mail merge data source. Read-only.

Syntax

expression .Name

expression A variable that represents an ODSOColumn object.

Return Value

String

See also

Concepts

ODSOColumn Object

Other resources

ODSOColumn Object Members


ODSOColumn.Parent Property (Office)

 Copy code hover
[image]

ODSOColumn.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ODSOColumn object. Read-only.

Syntax

expression .Parent

expression A variable that represents an ODSOColumn object.

Return Value

Object

See also

Concepts

ODSOColumn Object

Other resources

ODSOColumn Object Members


ODSOColumn.Value Property (Office)

 Copy code hover
[image]

ODSOColumn.Value Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the value of a data field in a mail merge data source. Read-only.

Syntax

expression .Value

expression A variable that represents an ODSOColumn object.

Return Value

String

See also

Concepts

ODSOColumn Object

Other resources

ODSOColumn Object Members


ODSOColumns Object (Office)

 Copy code hover
[image]

ODSOColumns Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of ODSOColumn objects that represent the data fields in a mail merge data source.

Example

Use the Columns property to return the ODSOColumns collection. The following example displays the field names in the data source attached to the active publication.

Copy code Copy code
Sub ShowFieldNames()
 Dim appOffice As OfficeDataSourceObject
 Dim intCount As Integer

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Columns
 For intCount = 1 To .Count
 MsgBox "Column Name: " & .Item(intCount).Name
 Next
 End With
End Sub

Use Columns(index), where index is the data field name or the index number, to return a single ODSOColumn object. The index number represents the position of the data field in the mail merge data source. This example retrieves the name of the first field and value of the first record of the FirstName field in the data source attached to the active publication.

Copy code Copy code
Sub GetDataFromSource()
 Dim appOffice As OfficeDataSourceObject

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Columns
 MsgBox "Field Name: " & .Columns(1).Name & _
 "Value: " & .Columns("FirstName").Value
 End With
End Sub

See also

Concepts

Object Model Reference

Other resources

ODSOColumns Object Members


ODSOColumns Members (Office)

 Copy code hover
[image]

ODSOColumns Members (Office)
Send feedback

Published: July 09, 2012

A collection of ODSOColumn objects that represent the data fields in a mail merge data source.

Methods

Name | Description
Item | Specifies an ODSOColumn object in the ODSOColumns collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ODSOColumns object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the ODSOColumns collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ODSOColumns object was created. Read-only.
Parent | Gets the Parent object for the ODSOColumns object. Read-only.


ODSOColumns Properties (Office)

 Copy code hover
[image]

ODSOColumns Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ODSOColumns object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the ODSOColumns collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ODSOColumns object was created. Read-only.
Parent | Gets the Parent object for the ODSOColumns object. Read-only.


ODSOColumns.Application Property (Office)

 Copy code hover
[image]

ODSOColumns.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ODSOColumns object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents an ODSOColumns object.

Return Value

Object

See also

Concepts

ODSOColumns Object

Other resources

ODSOColumns Object Members


ODSOColumns.Count Property (Office)

 Copy code hover
[image]

ODSOColumns.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the ODSOColumns collection. Read-only.

Syntax

expression .Count

expression A variable that represents an ODSOColumns object.

Return Value

Long

See also

Concepts

ODSOColumns Object

Other resources

ODSOColumns Object Members


ODSOColumns.Creator Property (Office)

 Copy code hover
[image]

ODSOColumns.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ODSOColumns object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents an ODSOColumns object.

Return Value

Long

See also

Concepts

ODSOColumns Object

Other resources

ODSOColumns Object Members


ODSOColumns.Parent Property (Office)

 Copy code hover
[image]

ODSOColumns.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ODSOColumns object. Read-only.

Syntax

expression .Parent

expression A variable that represents an ODSOColumns object.

Return Value

Object

See also

Concepts

ODSOColumns Object

Other resources

ODSOColumns Object Members


ODSOColumns Methods (Office)

 Copy code hover
[image]

ODSOColumns Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Item | Specifies an ODSOColumn object in the ODSOColumns collection.


ODSOColumns.Item Method (Office)

 Copy code hover
[image]

ODSOColumns.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Specifies an ODSOColumn object in the ODSOColumns collection.

Syntax

expression .Item(varIndex)

expression A variable that represents an ODSOColumns object.

Parameters

Name | Required/Optional | Data Type | Description
varIndex | Required | Variant | The index number of the item.

Return Value

Object

Example

The following example retrieves an ODSOColumn object from the ODSOColumns collection.

VBA Copy code Copy code
oOdsoColumn = oOdsoColumns.Item(2)

See also

Concepts

ODSOColumns Object

Other resources

ODSOColumns Object Members


ODSOFilter Object (Office)

 Copy code hover
[image]

ODSOFilter Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a filter to be applied to an attached mail merge data source. The ODSOFilter object is a member of the ODSOFilters object.

Remarks

Each filter is a line in a query string. Use the Column, Comparison, CompareTo, and Conjunction properties to return or set the data source query criterion.

Example

The following example changes an existing filter to remove from the mail merge all records that do not have a Region field equal to "WA".

Copy code Copy code
Sub SetQueryCriterion()
 Dim appOffice As Office.OfficeDataSourceObject
 Dim intItem As Integer

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Filters
 For intItem = 1 To .Count
 With .Item(intItem)
 If .Column = "Region" Then
 .Comparison = msoFilterComparisonNotEqual
 .CompareTo = "WA"
 If .Conjunction = "Or" Then .Conjunction = "And"
 End If
 End With
 Next intItem
 End With
End Sub

Use the Add method of the ODSOFilters object to add a new filter criterion to the query. This example adds a new line to the query string and then applies the combined filter to the data source.

Copy code Copy code
Sub SetQueryCriterion()
 Dim appOffice As OfficeDataSourceObject

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Filters
 .Add Column:="Region", _
 Comparison:=msoFilterComparisonIsBlank, _
 Conjunction:=msoFilterConjunctionAnd
 .ApplyFilter
 End With
End Sub

See also

Concepts

Object Model Reference

Other resources

ODSOFilter Object Members


ODSOFilter Members (Office)

 Copy code hover
[image]

ODSOFilter Members (Office)
Send feedback

Published: July 09, 2012

Represents a filter to be applied to an attached mail merge data source. The ODSOFilter object is a member of the ODSOFilters object.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ODSOFilter object (you can use this property with an Automation object to return that object's container application). Read-only.
Column | Gets or sets a String that represents the name of the field in the mail merge data source to use in the filter. Read/write.
CompareTo | Gets or sets a String that represents the text to compare in the query filter criterion. Read/write.
Comparison | Gets or sets an MsoFilterComparison constant that represents how to compare the Column and CompareTo properties. Read/write.
Conjunction | Gets or sets an MsoFilterConjunction constant that represents how a filter criterion relates to other filter criteria in the ODSOFilters object. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the ODSOFilter object was created. Read-only.
Index | Gets a Long representing the index number for an ODSOFilter object in the collection. Read-only.
Parent | Gets the Parent object for the ODSOFilter object. Read-only.


ODSOFilter Properties (Office)

 Copy code hover
[image]

ODSOFilter Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ODSOFilter object (you can use this property with an Automation object to return that object's container application). Read-only.
Column | Gets or sets a String that represents the name of the field in the mail merge data source to use in the filter. Read/write.
CompareTo | Gets or sets a String that represents the text to compare in the query filter criterion. Read/write.
Comparison | Gets or sets an MsoFilterComparison constant that represents how to compare the Column and CompareTo properties. Read/write.
Conjunction | Gets or sets an MsoFilterConjunction constant that represents how a filter criterion relates to other filter criteria in the ODSOFilters object. Read/write.
Creator | Gets a 32-bit integer that indicates the application in which the ODSOFilter object was created. Read-only.
Index | Gets a Long representing the index number for an ODSOFilter object in the collection. Read-only.
Parent | Gets the Parent object for the ODSOFilter object. Read-only.


ODSOFilter.Application Property (Office)

 Copy code hover
[image]

ODSOFilter.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ODSOFilter object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents an ODSOFilter object.

Return Value

Object

See also

Concepts

ODSOFilter Object

Other resources

ODSOFilter Object Members


ODSOFilter.Column Property (Office)

 Copy code hover
[image]

ODSOFilter.Column Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a String that represents the name of the field in the mail merge data source to use in the filter. Read/write.

Syntax

expression .Column

expression A variable that represents an ODSOFilter object.

Example

The following example changes an existing filter to remove from the mail merge all records that do not have a Region field equal to "WA".

Copy code Copy code
Sub SetQueryCriterion()
 Dim appOffice As Office.OfficeDataSourceObject
 Dim intItem As Integer

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Filters
 For intItem = 1 To .Count
 With .Item(intItem)
 If .Column = "Region" Then
 .Comparison = msoFilterComparisonNotEqual
 .CompareTo = "WA"
 If .Conjunction = "Or" Then .Conjunction = "And"
 End If
 End With
 Next intItem
 End With
End Sub

See also

Concepts

ODSOFilter Object
TextFrame2 Object

Other resources

ODSOFilter Object Members
TextFrame2 Object Members


ODSOFilter.CompareTo Property (Office)

 Copy code hover
[image]

ODSOFilter.CompareTo Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a String that represents the text to compare in the query filter criterion. Read/write.

Syntax

expression .CompareTo

expression A variable that represents an ODSOFilter object.

Example

The following example changes an existing filter to remove from the mail merge all records that do not have a Region field equal to "WA".

Copy code Copy code
Sub SetQueryCriterion()
 Dim appOffice As Office.OfficeDataSourceObject
 Dim intItem As Integer

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Filters
 For intItem = 1 To .Count
 With .Item(intItem)
 If .Column = "Region" Then
 .Comparison = msoFilterComparisonNotEqual
 .CompareTo = "WA"
 If .Conjunction = "Or" Then .Conjunction = "And"
 End If
 End With
 Next intItem
 End With
End Sub

See also

Concepts

ODSOFilter Object

Other resources

ODSOFilter Object Members


ODSOFilter.Comparison Property (Office)

 Copy code hover
[image]

ODSOFilter.Comparison Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets an MsoFilterComparison constant that represents how to compare the Column and CompareTo properties. Read/write.

Syntax

expression .Comparison

expression A variable that represents an ODSOFilter object.

Example

The following example changes an existing filter to remove from the mail merge all records that do not have a Region field equal to "WA".

Copy code Copy code
Sub SetQueryCriterion()
 Dim appOffice As Office.OfficeDataSourceObject
 Dim intItem As Integer

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Filters
 For intItem = 1 To .Count
 With .Item(intItem)
 If .Column = "Region" Then
 .Comparison = msoFilterComparisonNotEqual
 .CompareTo = "WA"
 If .Conjunction = "Or" Then .Conjunction = "And"
 End If
 End With
 Next intItem
 End With
End Sub

See also

Concepts

ODSOFilter Object

Other resources

ODSOFilter Object Members


ODSOFilter.Conjunction Property (Office)

 Copy code hover
[image]

ODSOFilter.Conjunction Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets an MsoFilterConjunction constant that represents how a filter criterion relates to other filter criteria in the ODSOFilters object. Read/write.

Syntax

expression .Conjunction

expression A variable that represents an ODSOFilter object.

Example

The following example changes an existing filter to remove from the mail merge all records that do not have a Region field equal to "WA".

Copy code Copy code
Sub SetQueryCriterion()
 Dim appOffice As Office.OfficeDataSourceObject
 Dim intItem As Integer

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Filters
 For intItem = 1 To .Count
 With .Item(intItem)
 If .Column = "Region" Then
 .Comparison = msoFilterComparisonNotEqual
 .CompareTo = "WA"
 If .Conjunction = "Or" Then .Conjunction = "And"
 End If
 End With
 Next intItem
 End With
End Sub

See also

Concepts

ODSOFilter Object

Other resources

ODSOFilter Object Members


ODSOFilter.Creator Property (Office)

 Copy code hover
[image]

ODSOFilter.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ODSOFilter object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents an ODSOFilter object.

Return Value

Long

See also

Concepts

ODSOFilter Object

Other resources

ODSOFilter Object Members


ODSOFilter.Index Property (Office)

 Copy code hover
[image]

ODSOFilter.Index Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long representing the index number for an ODSOFilter object in the collection. Read-only.

Syntax

expression .Index

expression A variable that represents an ODSOFilter object.

Return Value

Long

See also

Concepts

ODSOFilter Object

Other resources

ODSOFilter Object Members


ODSOFilter.Parent Property (Office)

 Copy code hover
[image]

ODSOFilter.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ODSOFilter object. Read-only.

Syntax

expression .Parent

expression A variable that represents an ODSOFilter object.

Return Value

Object

See also

Concepts

ODSOFilter Object

Other resources

ODSOFilter Object Members


ODSOFilters Object (Office)

 Copy code hover
[image]

ODSOFilters Object (Office)
See also Send feedback

Published: July 09, 2012

Represents all the filters to apply to the data source attached to the mail merge publication. The ODSOFilters object is composed of ODSOFilter objects.

Remarks

Use the Add method of the ODSOFilters object to add a new filter criterion to the query.

Example

This example adds a new line to the query string and then applies the combined filter to the data source.

Copy code Copy code
Sub SetQueryCriterion()
 Dim appOffice As OfficeDataSourceObject

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Filters
 .Add Column:="Region", _
 Comparison:=msoFilterComparisonIsBlank, _
 Conjunction:=msoFilterConjunctionAnd
 .ApplyFilter
 End With
End Sub

Use the Item method to access an individual filter criterion. This example loops through all the filter criterion and if it finds one with a value of "Region", changes it to remove from the mail merge all records that are not equal to "WA".

Copy code Copy code
Sub SetQueryCriterion()
 Dim appOffice As Office.OfficeDataSourceObject
 Dim intItem As Integer

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Filters
 For intItem = 1 To .Count
 With .Item(intItem)
 If .Column = "Region" Then
 .Comparison = msoFilterComparisonNotEqual
 .CompareTo = "WA"
 If .Conjunction = "Or" Then .Conjunction = "And"
 End If
 End With
 Next intItem
 End With
End Sub

See also

Concepts

Object Model Reference

Other resources

ODSOFilters Object Members


ODSOFilters Members (Office)

 Copy code hover
[image]

ODSOFilters Members (Office)
Send feedback

Published: July 09, 2012

Represents all the filters to apply to the data source attached to the mail merge publication. The ODSOFilters object is composed of ODSOFilter objects.

Methods

Name | Description
Add | Adds a new filter to the ODSOFilters collection.
Delete | Deletes a filter object from the ODSOFilters collection.
Item | Represents a ODSOFilter object in the ODSOFilters collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ODSOFilters object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the ODSOFilters collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ODSOFilters object was created. Read-only.
Parent | Gets the Parent object for the ODSOFilters object. Read-only.


ODSOFilters Properties (Office)

 Copy code hover
[image]

ODSOFilters Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ODSOFilters object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the ODSOFilters collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ODSOFilters object was created. Read-only.
Parent | Gets the Parent object for the ODSOFilters object. Read-only.


ODSOFilters.Application Property (Office)

 Copy code hover
[image]

ODSOFilters.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ODSOFilters object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents an ODSOFilters object.

Return Value

Object

See also

Concepts

ODSOFilters Object

Other resources

ODSOFilters Object Members


ODSOFilters.Count Property (Office)

 Copy code hover
[image]

ODSOFilters.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the ODSOFilters collection. Read-only.

Syntax

expression .Count

expression A variable that represents an ODSOFilters object.

Return Value

Long

See also

Concepts

ODSOFilters Object

Other resources

ODSOFilters Object Members


ODSOFilters.Creator Property (Office)

 Copy code hover
[image]

ODSOFilters.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ODSOFilters object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents an ODSOFilters object.

Return Value

Long

See also

Concepts

ODSOFilters Object

Other resources

ODSOFilters Object Members


ODSOFilters.Parent Property (Office)

 Copy code hover
[image]

ODSOFilters.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ODSOFilters object. Read-only.

Syntax

expression .Parent

expression A variable that represents an ODSOFilters object.

Return Value

Object

See also

Concepts

ODSOFilters Object

Other resources

ODSOFilters Object Members


ODSOFilters Methods (Office)

 Copy code hover
[image]

ODSOFilters Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a new filter to the ODSOFilters collection.
Delete | Deletes a filter object from the ODSOFilters collection.
Item | Represents a ODSOFilter object in the ODSOFilters collection.


ODSOFilters.Add Method (Office)

 Copy code hover
[image]

ODSOFilters.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a new filter to the ODSOFilters collection.

Syntax

expression .Add(Column, Comparison, Conjunction, bstrCompareTo, DeferUpdate)

expression Required. A variable that represents an ODSOFilters object.

Parameters

Name | Required/Optional | Data Type | Description
Column | Required | String | The name of the table in the data source.
Comparison | Required | MsoFilterComparison | How the data in the table is filtered.
Conjunction | Required | MsoFilterConjunction | Determines how this filter relates to other filters in the ODSOFilters object.
bstrCompareTo | Optional | String | If the Comparison argument is something other than msoFilterComparisonIsBlank or msoFilterComparisonIsNotBlank, a string to which the data in the table is compared.
DeferUpdate | Optional | Boolean | Specifies whether to delay updating the filter. Default is False.

See also

Concepts

ODSOFilters Object

Other resources

ODSOFilters Object Members


ODSOFilters.Delete Method (Office)

 Copy code hover
[image]

ODSOFilters.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes a filter object from the ODSOFilters collection.

Syntax

expression .Delete(Index, DeferUpdate)

expression Required. A variable that represents an ODSOFilters object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | The number of the filter to delete.
DeferUpdate | Optional | Boolean | Specifies whether to delay updating the filter. Default is False.

See also

Concepts

ODSOFilters Object

Other resources

ODSOFilters Object Members


ODSOFilters.Item Method (Office)

 Copy code hover
[image]

ODSOFilters.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Represents a ODSOFilter object in the ODSOFilters collection.

Syntax

expression .Item(Index)

expression A variable that represents an ODSOFilters object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | The number of the item.

Return Value

Object

Example

The following example retrieves an ODSOFilter object from the ODSOFilters collection.

VBA Copy code Copy code
oOdsoFilter = oOdsoFilters.Item(1)

See also

Concepts

ODSOFilters Object

Other resources

ODSOFilters Object Members


OfficeDataSourceObject Object (Office)

 Copy code hover
[image]

OfficeDataSourceObject Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the mail merge data source in a mail merge operation.

Remarks

To work with the OfficeDataSourceObject object, dimension a variable as an OfficeDataSourceObject object. You can then work with the different properties and methods associated with the object. Use the SetSortOrder method to specify how to sort the records in a data source.

Example

The following example sorts the data source first according to Postal Code in descending order, then on last name and first name in ascending order.

Copy code Copy code
Sub SetDataSortOrder()
 Dim appOffice As OfficeDataSourceObject

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 appOffice.SetSortOrder SortField1:="ZipCode", _
 SortAscending1:=False, SortField2:="LastName", _
 SortField3:="FirstName"
End Sub

Use the Column, Comparison, CompareTo, and Conjunction properties to return or set the data source query criterion. The following example changes an existing filter to remove from the mail merge all records that do not have a Region field equal to "WA".

Copy code Copy code
Sub SetQueryCriterion()
 Dim appOffice As Office.OfficeDataSourceObject
 Dim intItem As Integer

 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Filters
 For intItem = 1 To .Count
 With .Item(intItem)
 If .Column = "Region" Then
 .Comparison = msoFilterComparisonNotEqual
 .CompareTo = "WA"
 If .Conjunction = "Or" Then .Conjunction = "And"
 End If
 End With
 Next intItem
 End With
End Sub

See also

Concepts

Object Model Reference

Other resources

OfficeDataSourceObject Object Members


OfficeDataSourceObject Members (Office)

 Copy code hover
[image]

OfficeDataSourceObject Members (Office)
Send feedback

Published: July 09, 2012

Represents the mail merge data source in a mail merge operation.

Methods

Name | Description
ApplyFilter | Applies a filter to a mail merge data source to filter specified records meeting specified criteria.
Move | Moves a record in a return set from a OfficeDataSourceObject object from one position to another.
Open | Opens a table in a OfficeDataSourceObject object.
SetSortOrder | Sets the sort order for mail merge data.

Properties

Name | Description
Columns | Gets an ODSOColumns object that represents the fields in a data source. Read-only.
ConnectString | Gets or sets a String that represents the connection to the specified mail merge data source. Read/write.
DataSource | Gets or sets a String that represents the name of the attached data source. Read/write.
Filters | Gets the filter status for a OfficeDataSourceObject object. Read-only.
RowCount | Gets a Long that represents the number of records in the specified data source. Read-only.
Table | Gets a String that represents the name of the table within the data source file that contains the mail merge records. The returned value may be blank if the table name is unknown or not applicable to the current data source. Read-only.


OfficeDataSourceObject Properties (Office)

 Copy code hover
[image]

OfficeDataSourceObject Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Columns | Gets an ODSOColumns object that represents the fields in a data source. Read-only.
ConnectString | Gets or sets a String that represents the connection to the specified mail merge data source. Read/write.
DataSource | Gets or sets a String that represents the name of the attached data source. Read/write.
Filters | Gets the filter status for a OfficeDataSourceObject object. Read-only.
RowCount | Gets a Long that represents the number of records in the specified data source. Read-only.
Table | Gets a String that represents the name of the table within the data source file that contains the mail merge records. The returned value may be blank if the table name is unknown or not applicable to the current data source. Read-only.


OfficeDataSourceObject.Columns Property (Office)

 Copy code hover
[image]

OfficeDataSourceObject.Columns Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an ODSOColumns object that represents the fields in a data source. Read-only.

Syntax

expression .Columns

expression A variable that represents an OfficeDataSourceObject object.

Example

The following example displays the field names in the data source attached to the active publication.

Copy code Copy code
Sub ShowFieldNames()
 Dim appOffice As OfficeDataSourceObject
 Dim intCount As Integer

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 With appOffice.Columns
 For intCount = 1 To .Count
 MsgBox "Field Name: " & .Item(intCount).Name
 Next
 End With
End Sub

See also

Concepts

OfficeDataSourceObject Object

Other resources

OfficeDataSourceObject Object Members


OfficeDataSourceObject.ConnectString Property (Office)

 Copy code hover
[image]

OfficeDataSourceObject.ConnectString Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a String that represents the connection to the specified mail merge data source. Read/write.

Syntax

expression .ConnectString

expression A variable that represents an OfficeDataSourceObject object.

Example

This example checks if the connection string contains the characters ODSOOutlook and displays a message accordingly.

Copy code Copy code
Sub VerifyCorrectDataSource()
 Dim appOffice As OfficeDataSourceObject

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 If InStr(appOffice.ConnectString, "ODSOOutlook") > 0 Then
 MsgBox "Your Outlook address book is used as the data source."
 Else
 MsgBox "Your Outlook address book is not used as the data source."
 End If

End Sub

See also

Concepts

OfficeDataSourceObject Object

Other resources

OfficeDataSourceObject Object Members


OfficeDataSourceObject.DataSource Property (Office)

 Copy code hover
[image]

OfficeDataSourceObject.DataSource Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a String that represents the name of the attached data source. Read/write.

Syntax

expression .DataSource

expression A variable that represents an OfficeDataSourceObject object.

Example

The following example sets the name of the data source if the name is blank.

Copy code Copy code
Sub SetAndReturnDataSourceName()
 Dim appOffice As OfficeDataSourceObject

 Set appOffice = Application.OfficeDataSourceObject
 With appOffice
 .Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 If .DataSource = "" Then
 .DataSource = "Northwind"
 MsgBox .DataSource
 End If
 End With
End Sub

See also

Concepts

OfficeDataSourceObject Object

Other resources

OfficeDataSourceObject Object Members


OfficeDataSourceObject.Filters Property (Office)

 Copy code hover
[image]

OfficeDataSourceObject.Filters Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the filter status for a OfficeDataSourceObject object. Read-only.

Syntax

expression .Filters

expression A variable that represents an OfficeDataSourceObject object.

Return Value

Object

See also

Concepts

OfficeDataSourceObject Object

Other resources

OfficeDataSourceObject Object Members


OfficeDataSourceObject.RowCount Property (Office)

 Copy code hover
[image]

OfficeDataSourceObject.RowCount Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long that represents the number of records in the specified data source. Read-only.

Syntax

expression .RowCount

expression A variable that represents an OfficeDataSourceObject object.

Example

This example adds a new filter that removes all records with a blank Region field and then applies the filter to the active publication.

Copy code Copy code
Sub OfficeFilters()
 Dim appOffice As OfficeDataSourceObject
 Dim appFilters As ODSOFilters

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 Set appFilters = appOffice.Filters

 MsgBox appOffice.RowCount

 appFilters.Add Column:="Region", Comparison:=msoFilterComparisonEqual, _
 Conjunction:=msoFilterConjunctionAnd, bstrCompareTo:="WA"
 appOffice.ApplyFilter

 MsgBox appOffice.RowCount

End Sub

See also

Concepts

OfficeDataSourceObject Object

Other resources

OfficeDataSourceObject Object Members


OfficeDataSourceObject.Table Property (Office)

 Copy code hover
[image]

OfficeDataSourceObject.Table Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a String that represents the name of the table within the data source file that contains the mail merge records. The returned value may be blank if the table name is unknown or not applicable to the current data source. Read-only.

Syntax

expression .Table

expression A variable that represents an OfficeDataSourceObject object.

Example

This example sets the name of the table if the table name is currently blank.

Copy code Copy code
Sub OfficeTest()

 Dim appOffice As OfficeDataSourceObject

 Set appOffice = Application.OfficeDataSourceObject
 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 If appOffice.Table = "" Then
 appOffice.Table = "Employees"
 End If

End Sub

See also

Concepts

OfficeDataSourceObject Object

Other resources

OfficeDataSourceObject Object Members


OfficeDataSourceObject Methods (Office)

 Copy code hover
[image]

OfficeDataSourceObject Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
ApplyFilter | Applies a filter to a mail merge data source to filter specified records meeting specified criteria.
Move | Moves a record in a return set from a OfficeDataSourceObject object from one position to another.
Open | Opens a table in a OfficeDataSourceObject object.
SetSortOrder | Sets the sort order for mail merge data.


OfficeDataSourceObject.ApplyFilter Method (Office)

 Copy code hover
[image]

OfficeDataSourceObject.ApplyFilter Method (Office)
See also Send feedback

Published: July 09, 2012

Applies a filter to a mail merge data source to filter specified records meeting specified criteria.

Syntax

expression .ApplyFilter

expression A variable that represents an OfficeDataSourceObject object.

Example

This example adds a new filter that removes all records with a blank Region field and then applies the filter to the active publication.

Copy code Copy code
Sub OfficeFilters()
 Dim appOffice As OfficeDataSourceObject
 Dim appFilters As ODSOFilters

 Set appOffice = Application.OfficeDataSourceObject

 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 Set appFilters = appOffice.Filters

 MsgBox appOffice.RowCount

 appFilters.Add Column:="Region", Comparison:=msoFilterComparisonEqual, _
 Conjunction:=msoFilterConjunctionAnd, bstrCompareTo:="WA"
 appOffice.ApplyFilter

 MsgBox appOffice.RowCount

End Sub

See also

Concepts

OfficeDataSourceObject Object

Other resources

OfficeDataSourceObject Object Members


OfficeDataSourceObject.Move Method (Office)

 Copy code hover
[image]

OfficeDataSourceObject.Move Method (Office)
See also Send feedback

Published: July 09, 2012

Moves a record in a return set from a OfficeDataSourceObject object from one position to another.

Syntax

expression .Move(MsoMoveRow, RowNbr)

expression A variable that represents an OfficeDataSourceObject object.

Parameters

Name | Required/Optional | Data Type | Description
MsoMoveRow | Required | MsoMoveRow | A constant specifying which row to move.
RowNbr | Optional | Integer | The number of the destination row.

Return Value

Integer

Example

The following example moves the first row in the set of records to the third row.

VBA Copy code Copy code
oOdso.Move(msoMoveRowFirst, 3)

See also

Concepts

OfficeDataSourceObject Object

Other resources

OfficeDataSourceObject Object Members


OfficeDataSourceObject.Open Method (Office)

 Copy code hover
[image]

OfficeDataSourceObject.Open Method (Office)
See also Send feedback

Published: July 09, 2012

Opens a table in a OfficeDataSourceObject object.

Syntax

expression .Open(bstrSrc, bstrConnect, bstrTable, fOpenExclusive, fNeverPrompt)

expression A variable that represents an OfficeDataSourceObject object.

Parameters

Name | Required/Optional | Data Type | Description
bstrSrc | Optional | String | Contains the name of the data source.
bstrConnect | Optional | String | Contains the connection string to the data source.
bstrTable | Optional | String | Specifies which table to open.
fOpenExclusive | Optional | Long | Indicates whether the table should be opened for exclusive access.
fNeverPrompt | Optional | Long | Indicates whether to notify the user if the table can not be opened.

See also

Concepts

OfficeDataSourceObject Object

Other resources

OfficeDataSourceObject Object Members


OfficeDataSourceObject.SetSortOrder Method (Office)

 Copy code hover
[image]

OfficeDataSourceObject.SetSortOrder Method (Office)
See also Send feedback

Published: July 09, 2012

Sets the sort order for mail merge data.

Syntax

expression .SetSortOrder(SortField1, SortAscending1, SortField2, SortAscending2, SortField3, SortAscending3)

expression A variable that represents an OfficeDataSourceObject object.

Parameters

Name | Required/Optional | Data Type | Description
SortField1 | Required | String | The first field on which to sort the mail merge data.
SortAscending1 | Optional | Boolean | True (default) to perform an ascending sort on SortField1; False to perform a descending sort.
SortField2 | Optional | String | The second field on which to sort the mail merge data. Default is an empty string.
SortAscending2 | Optional | Boolean | True (default) to perform an ascending sort on SortField2; False to perform a descending sort.
SortField3 | Optional | String | The third field on which to sort the mail merge data. Default is an empty string.
SortAscending3 | Optional | Boolean | True (default) to perform an ascending sort on SortField3; False to perform a descending sort.

Example

The following example sorts the data source first according to Postal Code in descending order, then on last name and first name in ascending order.

Copy code Copy code
Sub SetDataSortOrder()
 Dim appOffice As OfficeDataSourceObject

 Set appOffice = Application.OfficeDataSourceObject

 appOffice.Open bstrConnect:="DRIVER=SQL Server;SERVER=ServerName;" & _
 "UID=user;PWD=;DATABASE=Northwind", bstrTable:="Employees"

 appOffice.SetSortOrder SortField1:="ZipCode", _
 SortAscending1:=False, SortField2:="LastName", _
 SortField3:="FirstName"
End Sub

See also

Concepts

OfficeDataSourceObject Object

Other resources

OfficeDataSourceObject Object Members


OfficeTheme Object (Office)

 Copy code hover
[image]

OfficeTheme Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a Microsoft Office theme.

Example

The following example sets a ThemeColorScheme of an OfficeTheme object.

VBA Copy code Copy code
Dim tTheme As OfficeTheme
Dim tcsThemeColorScheme As ThemeColorScheme
Set tcsThemeColorScheme = tTheme.ThemeColorScheme

See also

Concepts

Object Model Reference

Other resources

OfficeTheme Object Members


OfficeTheme Members (Office)

 Copy code hover
[image]

OfficeTheme Members (Office)
Send feedback

Published: July 09, 2012

Represents a Microsoft Office theme.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the OfficeTheme object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the OfficeTheme object was created. Read-only.
Parent | Gets the Parent object for the OfficeTheme object. Read-only.
ThemeColorScheme | Gets a ThemeColorScheme object that represents the color scheme of a Microsoft Office theme. Read-only.
ThemeEffectScheme | Gets a ThemeEffectScheme object that represents the effects scheme of a Microsoft Office theme. Read-only.
ThemeFontScheme | Gets a ThemeFontScheme object that represents the font scheme of a Microsoft Office theme. Read-only.


OfficeTheme Properties (Office)

 Copy code hover
[image]

OfficeTheme Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the OfficeTheme object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the OfficeTheme object was created. Read-only.
Parent | Gets the Parent object for the OfficeTheme object. Read-only.
ThemeColorScheme | Gets a ThemeColorScheme object that represents the color scheme of a Microsoft Office theme. Read-only.
ThemeEffectScheme | Gets a ThemeEffectScheme object that represents the effects scheme of a Microsoft Office theme. Read-only.
ThemeFontScheme | Gets a ThemeFontScheme object that represents the font scheme of a Microsoft Office theme. Read-only.


OfficeTheme.Application Property (Office)

 Copy code hover
[image]

OfficeTheme.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the OfficeTheme object. Read-only.

Syntax

expression .Application

expression An expression that returns a OfficeTheme object.

Return Value

Object

See also

Concepts

OfficeTheme Object

Other resources

OfficeTheme Object Members


OfficeTheme.Creator Property (Office)

 Copy code hover
[image]

OfficeTheme.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the OfficeTheme object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a OfficeTheme object.

Return Value

Long

See also

Concepts

OfficeTheme Object

Other resources

OfficeTheme Object Members


OfficeTheme.Parent Property (Office)

 Copy code hover
[image]

OfficeTheme.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the OfficeTheme object. Read-only.

Syntax

expression .Parent

expression An expression that returns a OfficeTheme object.

Return Value

Object

See also

Concepts

OfficeTheme Object

Other resources

OfficeTheme Object Members


OfficeTheme.ThemeColorScheme Property (Office)

 Copy code hover
[image]

OfficeTheme.ThemeColorScheme Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a ThemeColorScheme object that represents the color scheme of a Microsoft Office theme. Read-only.

Syntax

expression .ThemeColorScheme

expression An expression that returns a OfficeTheme object.

Return Value

ThemeColorScheme

See also

Concepts

OfficeTheme Object

Other resources

OfficeTheme Object Members


OfficeTheme.ThemeEffectScheme Property (Office)

 Copy code hover
[image]

OfficeTheme.ThemeEffectScheme Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a ThemeEffectScheme object that represents the effects scheme of a Microsoft Office theme. Read-only.

Syntax

expression .ThemeEffectScheme

expression An expression that returns a OfficeTheme object.

Return Value

ThemeEffectScheme

See also

Concepts

OfficeTheme Object

Other resources

OfficeTheme Object Members


OfficeTheme.ThemeFontScheme Property (Office)

 Copy code hover
[image]

OfficeTheme.ThemeFontScheme Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a ThemeFontScheme object that represents the font scheme of a Microsoft Office theme. Read-only.

Syntax

expression .ThemeFontScheme

expression An expression that returns a OfficeTheme object.

Return Value

ThemeFontScheme

See also

Concepts

OfficeTheme Object

Other resources

OfficeTheme Object Members


ParagraphFormat2 Object (Office)

 Copy code hover
[image]

ParagraphFormat2 Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the paragraph formatting of a text range.

Example

The following example left aligns the paragraphs in shape two on slide one in the active PowerPoint presentation.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(2).TextFrame2.TextRange2 _
 .ParagraphFormat2.Alignment = ppAlignLeft

See also

Concepts

Object Model Reference

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2 Members (Office)

 Copy code hover
[image]

ParagraphFormat2 Members (Office)
Send feedback

Published: July 09, 2012

Represents the paragraph formatting of a text range.

Properties

Name | Description
Alignment | Gets or sets a value specifying the alignment of the paragraph. Read/write.
Application | Gets an object that represents the application that contains the object. Read-only.
BaselineAlignment | Gets or sets a constant that represents the vertical position of fonts in a paragraph. Read/write.
Bullet | Gets a BulletFormat2 object for the paragraph. Read-only.
Creator | Gets a value representing the application that created the ParagraphFormat2 object. Read-only.
FarEastLineBreakLevel | Gets or sets the East Asian line break control level for the specified paragraph. Read/write.
FirstLineIndent | Gets or sets the value (in points) for a first line or hanging indent. Read/write.
HangingPunctuation | Determines whether hanging punctuation is enabled for the specified paragraphs. Read/write.
IndentLevel | Gets or sets a value representing the indent level assigned to text in the selected paragraph. Read/write.
LeftIndent | Gets or sets a value that represents the left indent value (in points) for the specified paragraphs. Read/write.
LineRuleAfter | Determines whether line spacing after the last line in each paragraph is set to a specific number of points or lines. Read/write.
LineRuleBefore | Determines whether line spacing before the first line in each paragraph is set to a specific number of points or lines. Read/write.
LineRuleWithin | Determines whether line spacing between base lines is set to a specific number of points or lines. Read/write.
Parent | Gets the parent object for the ParagraphFormat2 object. Read-only.
RightIndent | Gets or sets the right indent (in points) for the specified paragraphs. Read/write.
SpaceAfter | Gets or sets the amount of spacing (in points) after the specified paragraph. Read/write.
SpaceBefore | Gets or sets the spacing (in points) before the specified paragraphs. Read/write.
SpaceWithin | Gets or sets the amount of space between base lines in the specified paragraph, in points or lines. Read/write.
TabStops | Gets a TabStops2 collection that represents all the custom tab stops for the specified paragraphs. Read-only.
TextDirection | Gets or sets the text direction for the specified paragraph. Read/write.
WordWrap | Determines whether the application wraps the Latin text in the middle of a word in the specified paragraphs. Read/write.


ParagraphFormat2 Properties (Office)

 Copy code hover
[image]

ParagraphFormat2 Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Alignment | Gets or sets a value specifying the alignment of the paragraph. Read/write.
Application | Gets an object that represents the application that contains the object. Read-only.
BaselineAlignment | Gets or sets a constant that represents the vertical position of fonts in a paragraph. Read/write.
Bullet | Gets a BulletFormat2 object for the paragraph. Read-only.
Creator | Gets a value representing the application that created the ParagraphFormat2 object. Read-only.
FarEastLineBreakLevel | Gets or sets the East Asian line break control level for the specified paragraph. Read/write.
FirstLineIndent | Gets or sets the value (in points) for a first line or hanging indent. Read/write.
HangingPunctuation | Determines whether hanging punctuation is enabled for the specified paragraphs. Read/write.
IndentLevel | Gets or sets a value representing the indent level assigned to text in the selected paragraph. Read/write.
LeftIndent | Gets or sets a value that represents the left indent value (in points) for the specified paragraphs. Read/write.
LineRuleAfter | Determines whether line spacing after the last line in each paragraph is set to a specific number of points or lines. Read/write.
LineRuleBefore | Determines whether line spacing before the first line in each paragraph is set to a specific number of points or lines. Read/write.
LineRuleWithin | Determines whether line spacing between base lines is set to a specific number of points or lines. Read/write.
Parent | Gets the parent object for the ParagraphFormat2 object. Read-only.
RightIndent | Gets or sets the right indent (in points) for the specified paragraphs. Read/write.
SpaceAfter | Gets or sets the amount of spacing (in points) after the specified paragraph. Read/write.
SpaceBefore | Gets or sets the spacing (in points) before the specified paragraphs. Read/write.
SpaceWithin | Gets or sets the amount of space between base lines in the specified paragraph, in points or lines. Read/write.
TabStops | Gets a TabStops2 collection that represents all the custom tab stops for the specified paragraphs. Read-only.
TextDirection | Gets or sets the text direction for the specified paragraph. Read/write.
WordWrap | Determines whether the application wraps the Latin text in the middle of a word in the specified paragraphs. Read/write.


ParagraphFormat2.Alignment Property (Office)

 Copy code hover
[image]

ParagraphFormat2.Alignment Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value specifying the alignment of the paragraph. Read/write.

Syntax

expression .Alignment

expression An expression that returns a ParagraphFormat2 object.

Return Value

MsoParagraphAlignment

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.Application Property (Office)

 Copy code hover
[image]

ParagraphFormat2.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an object that represents the application that contains the object. Read-only.

Syntax

expression .Application

expression An expression that returns a ParagraphFormat2 object.

Return Value

Object

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.BaselineAlignment Property (Office)

 Copy code hover
[image]

ParagraphFormat2.BaselineAlignment Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a constant that represents the vertical position of fonts in a paragraph. Read/write.

Syntax

expression .BaselineAlignment

expression An expression that returns a ParagraphFormat2 object.

Return Value

MsoBaselineAlignment

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.Bullet Property (Office)

 Copy code hover
[image]

ParagraphFormat2.Bullet Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a BulletFormat2 object for the paragraph. Read-only.

Syntax

expression .Bullet

expression An expression that returns a ParagraphFormat2 object.

Return Value

BulletFormat2

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.Creator Property (Office)

 Copy code hover
[image]

ParagraphFormat2.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value representing the application that created the ParagraphFormat2 object. Read-only.

Syntax

expression .Creator

expression An expression that returns a ParagraphFormat2 object.

Return Value

Long

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.FarEastLineBreakLevel Property (Office)

 Copy code hover
[image]

ParagraphFormat2.FarEastLineBreakLevel Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the East Asian line break control level for the specified paragraph. Read/write.

Syntax

expression .FarEastLineBreakLevel

expression An expression that returns a ParagraphFormat2 object.

Return Value

MsoTriState

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.FirstLineIndent Property (Office)

 Copy code hover
[image]

ParagraphFormat2.FirstLineIndent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the value (in points) for a first line or hanging indent. Read/write.

Syntax

expression .FirstLineIndent

expression An expression that returns a ParagraphFormat2 object.

Return Value

Single

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.HangingPunctuation Property (Office)

 Copy code hover
[image]

ParagraphFormat2.HangingPunctuation Property (Office)
See also Send feedback

Published: July 09, 2012

Determines whether hanging punctuation is enabled for the specified paragraphs. Read/write.

Syntax

expression .HangingPunctuation

expression An expression that returns a ParagraphFormat2 object.

Return Value

MsoTriState

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.IndentLevel Property (Office)

 Copy code hover
[image]

ParagraphFormat2.IndentLevel Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value representing the indent level assigned to text in the selected paragraph. Read/write.

Syntax

expression .IndentLevel

expression An expression that returns a ParagraphFormat2 object.

Return Value

Integer

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.LeftIndent Property (Office)

 Copy code hover
[image]

ParagraphFormat2.LeftIndent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value that represents the left indent value (in points) for the specified paragraphs. Read/write.

Syntax

expression .LeftIndent

expression An expression that returns a ParagraphFormat2 object.

Return Value

Single

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.LineRuleAfter Property (Office)

 Copy code hover
[image]

ParagraphFormat2.LineRuleAfter Property (Office)
See also Send feedback

Published: July 09, 2012

Determines whether line spacing after the last line in each paragraph is set to a specific number of points or lines. Read/write.

Syntax

expression .LineRuleAfter

expression An expression that returns a ParagraphFormat2 object.

Return Value

MsoTriState

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.LineRuleBefore Property (Office)

 Copy code hover
[image]

ParagraphFormat2.LineRuleBefore Property (Office)
See also Send feedback

Published: July 09, 2012

Determines whether line spacing before the first line in each paragraph is set to a specific number of points or lines. Read/write.

Syntax

expression .LineRuleBefore

expression An expression that returns a ParagraphFormat2 object.

Return Value

MsoTriState

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.LineRuleWithin Property (Office)

 Copy code hover
[image]

ParagraphFormat2.LineRuleWithin Property (Office)
See also Send feedback

Published: July 09, 2012

Determines whether line spacing between base lines is set to a specific number of points or lines. Read/write.

Syntax

expression .LineRuleWithin

expression An expression that returns a ParagraphFormat2 object.

Return Value

MsoTriState

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.Parent Property (Office)

 Copy code hover
[image]

ParagraphFormat2.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the parent object for the ParagraphFormat2 object. Read-only.

Syntax

expression .Parent

expression An expression that returns a ParagraphFormat2 object.

Return Value

Object

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.RightIndent Property (Office)

 Copy code hover
[image]

ParagraphFormat2.RightIndent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the right indent (in points) for the specified paragraphs. Read/write.

Syntax

expression .RightIndent

expression An expression that returns a ParagraphFormat2 object.

Return Value

Single

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.SpaceAfter Property (Office)

 Copy code hover
[image]

ParagraphFormat2.SpaceAfter Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the amount of spacing (in points) after the specified paragraph. Read/write.

Syntax

expression .SpaceAfter

expression An expression that returns a ParagraphFormat2 object.

Return Value

Single

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.SpaceBefore Property (Office)

 Copy code hover
[image]

ParagraphFormat2.SpaceBefore Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the spacing (in points) before the specified paragraphs. Read/write.

Syntax

expression .SpaceBefore

expression An expression that returns a ParagraphFormat2 object.

Return Value

Single

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.SpaceWithin Property (Office)

 Copy code hover
[image]

ParagraphFormat2.SpaceWithin Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the amount of space between base lines in the specified paragraph, in points or lines. Read/write.

Syntax

expression .SpaceWithin

expression An expression that returns a ParagraphFormat2 object.

Return Value

Single

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.TabStops Property (Office)

 Copy code hover
[image]

ParagraphFormat2.TabStops Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a TabStops2 collection that represents all the custom tab stops for the specified paragraphs. Read-only.

Syntax

expression .TabStops

expression An expression that returns a ParagraphFormat2 object.

Return Value

TabStops2

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.TextDirection Property (Office)

 Copy code hover
[image]

ParagraphFormat2.TextDirection Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the text direction for the specified paragraph. Read/write.

Syntax

expression .TextDirection

expression An expression that returns a ParagraphFormat2 object.

Return Value

MsoTextDirection

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


ParagraphFormat2.WordWrap Property (Office)

 Copy code hover
[image]

ParagraphFormat2.WordWrap Property (Office)
See also Send feedback

Published: July 09, 2012

Determines whether the application wraps the Latin text in the middle of a word in the specified paragraphs. Read/write.

Syntax

expression .WordWrap

expression An expression that returns a ParagraphFormat2 object.

Return Value

MsoTriState

See also

Concepts

ParagraphFormat2 Object

Other resources

ParagraphFormat2 Object Members


Permission Object (Office)

 Copy code hover
[image]

Permission Object (Office)
See also Send feedback

Published: July 09, 2012

The Permission property of the Document object in Microsoft Word, a Workbook object in Microsoft Excel, and a Presentation object in Microsoft PowerPoint returns a Permission object.

Remarks

Use the Permission object to restrict permissions to the active document and to return or set specific permissions settings.

The Permission object gives access to a collection of UserPermission objects. Use the UserPermission object to associate specific sets of rights with individual users. While some permissions granted through the user interface (such as msoPermissionPrint) apply to all users, you can use the UserPermission object to assign them on a per-user basis with per-user expiration dates.

Microsoft Office Information Rights Management supports the use of administrative permission policies which list users and groups and their document permissions. Use the ApplyPolicy method to apply a permission policy, and the PermissionFromPolicy, PolicyName, and PolicyDescription properties to return policy information.

The Permission object model is available whether permissions are restricted on the active document or not . The Permission property of the Document, Workbook, and Presentation objects does not return Nothing when the active document does not have restricted permissions. Use the Enabled property to determine whether a document has restricted permissions.

Use of the Permission object raises an error when the Windows Rights Management client is not installed.

Example

The following example returns information about the permissions settings on the active document.

VBA Copy code Copy code
Dim irmPermission As Office.Permission
 Dim strIRMInfo As String
 Set irmPermission = ActiveWorkbook.Permission
 If irmPermission.Enabled Then
 strIRMInfo = "Permissions are restricted on this document." & vbCrLf
 strIRMInfo = strIRMInfo & " View in trusted browser: " & _
 irmPermission.EnableTrustedBrowser & vbCrLf & _
 " Document author: " & irmPermission.DocumentAuthor & vbCrLf & _
 " Users with permissions: " & irmPermission.Count & vbCrLf & _
 " Cache licenses: " & irmPermission.StoreLicenses & vbCrLf & _
 " Request permission URL: " & irmPermission.RequestPermissionURL & vbCrLf
 If irmPermission.PermissionFromPolicy Then
 strIRMInfo = strIRMInfo & " Permissions applied from policy:" & vbCrLf & _
 " Policy name: " & irmPermission.PolicyName & vbCrLf & _
 " Policy description: " & irmPermission.PolicyDescription
 Else
 strIRMInfo = strIRMInfo & " Default permissions applied." & vbCrLf & _
 " Default policy name: " & irmPermission.PolicyName & vbCrLf & _
 " Default policy description: " & irmPermission.PolicyDescription
 End If
 Else
 strIRMInfo = "Permissions are NOT restricted on this document."
 End If
 MsgBox strIRMInfo, vbInformation + vbOKOnly, "IRM Information"
 Set irmPermission = Nothing

See also

Concepts

Object Model Reference

Other resources

Permission Object Members


Permission Members (Office)

 Copy code hover
[image]

Permission Members (Office)
Send feedback

Published: July 09, 2012

The Permission property of the Document object in Microsoft Word, a Workbook object in Microsoft Excel, and a Presentation object in Microsoft PowerPoint returns a Permission object.

Methods

Name | Description
Add | Creates a set of permissions on the active document for the specified user. Returns a UserPermission object.
ApplyPolicy | Applies the specified permission policy to the active document.
RemoveAll | Removes all UserPermission objects from the Permission collection of the active document.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the Permission object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the Permission object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the Permission object was created. Read-only.
DocumentAuthor | Gets or sets the name in e-mail form of the author of the active document. Read/write.
Enabled | Gets or sets a Boolean value that indicates whether permissions are enabled on the active document. Read/write.
EnableTrustedBrowser | Gets or sets a value indicating whether to enable a browser from a trusted source. Read/write.
Item | Gets a UserPermission object that is a member of the Permission collection. The UserPermission object associates a set of permissions on the active document with a single user and an optional expiration date. Read-only.
Parent | Gets the Parent object for the Permission object. Read-only.
PermissionFromPolicy | Gets a Boolean value that indicates whether a permission policy has been applied to the active document. Read-only.
PolicyDescription | Gets the description of the permissions policy applied to the active document. Read-only.
PolicyName | Gets the name of the permissions policy applied to the active document. Read-only.
RequestPermissionURL | Gets or sets the file or Web site URL to visit or the e-mail address to contact for users who need additional permissions on the active document. Read/write.
StoreLicenses | Gets or sets a Boolean value that indicates whether the user's license to view the active document should be cached to allow offline viewing when the user cannot connect to a rights management server. Read/write.


Permission Properties (Office)

 Copy code hover
[image]

Permission Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the Permission object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the Permission object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the Permission object was created. Read-only.
DocumentAuthor | Gets or sets the name in e-mail form of the author of the active document. Read/write.
Enabled | Gets or sets a Boolean value that indicates whether permissions are enabled on the active document. Read/write.
EnableTrustedBrowser | Gets or sets a value indicating whether to enable a browser from a trusted source. Read/write.
Item | Gets a UserPermission object that is a member of the Permission collection. The UserPermission object associates a set of permissions on the active document with a single user and an optional expiration date. Read-only.
Parent | Gets the Parent object for the Permission object. Read-only.
PermissionFromPolicy | Gets a Boolean value that indicates whether a permission policy has been applied to the active document. Read-only.
PolicyDescription | Gets the description of the permissions policy applied to the active document. Read-only.
PolicyName | Gets the name of the permissions policy applied to the active document. Read-only.
RequestPermissionURL | Gets or sets the file or Web site URL to visit or the e-mail address to contact for users who need additional permissions on the active document. Read/write.
StoreLicenses | Gets or sets a Boolean value that indicates whether the user's license to view the active document should be cached to allow offline viewing when the user cannot connect to a rights management server. Read/write.


Permission.Application Property (Office)

 Copy code hover
[image]

Permission.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the Permission object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a Permission object.

Return Value

Object

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.Count Property (Office)

 Copy code hover
[image]

Permission.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the Permission object. Read-only.

Syntax

expression .Count

expression A variable that represents a Permission object.

Return Value

Long

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.Creator Property (Office)

 Copy code hover
[image]

Permission.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the Permission object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a Permission object.

Return Value

Long

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.DocumentAuthor Property (Office)

 Copy code hover
[image]

Permission.DocumentAuthor Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the name in e-mail form of the author of the active document. Read/write.

Syntax

expression .DocumentAuthor

expression A variable that represents a Permission object.

Remarks

The DocumentAuthor property returns or sets the author of the active document. The author always has non-expiring owner rights to the document, whether owner permission is granted explicitly (through a UserPermission object) or not.

The DocumentAuthor property can only be changed to a different account that has been certified through the permissions user interface to open restricted content on the local computer. In most cases, users who have a single Windows account can only choose between their Windows and their Passport identities.

If the user's Microsoft Windows and Passport identities use the same e-mail address, then use the format passport:someone@example.com to specify the Passport identity as the DocumentAuthor property.

Example

The following example displays information about the permissions settings of the active document, including the document author.

Copy code Copy code
 Dim irmPermission As Office.Permission
 Dim strIRMInfo As String
 Set irmPermission = ActiveWorkbook.Permission
 If irmPermission.Enabled Then
 strIRMInfo = "Permissions are enabled on this document." & vbCrLf
 strIRMInfo = strIRMInfo & " View in trusted browser: " & _
 irmPermission.EnableTrustedBrowser & vbCrLf & _
 " Document author: " & irmPermission.DocumentAuthor & vbCrLf & _
 " Users with rights: " & irmPermission.Count & vbCrLf & _
 " Cache licenses locally: " & irmPermission.StoreLicenses & vbCrLf & _
 " Request permission URL: " & irmPermission.RequestPermissionURL & vbCrLf
 If irmPermission.PermissionFromPolicy Then
 strIRMInfo = strIRMInfo & " Permissions applied from policy:" & vbCrLf & _
 " Policy name: " & irmPermission.PolicyName & vbCrLf & _
 " Policy description: " & irmPermission.PolicyDescription
 Else
 strIRMInfo = strIRMInfo & " Default permissions applied."
 End If
 Else
 strIRMInfo = "Permissions are NOT enabled on this document."
 End If
 MsgBox strIRMInfo, vbInformation + vbOKOnly, "IRM Information"
 Set irmPermission = Nothing

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.Enabled Property (Office)

 Copy code hover
[image]

Permission.Enabled Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a Boolean value that indicates whether permissions are enabled on the active document. Read/write.

Syntax

expression .Enabled

expression Required. A variable that represents a Permission object.

Remarks

Use the Enabled property to determine whether permissions are restricted on the active document, and to enable or disable permissions. Set Enabled to False to disable permissions and to remove all users, other than the document author, and their permissions.

When permissions are disabled, the Count property of the Permission object returns 0 (zero); however, when permissions are re-enabled, the permissions of the document author remain intact.

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.EnableTrustedBrowser Property (Office)

 Copy code hover
[image]

Permission.EnableTrustedBrowser Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value indicating whether to enable a browser from a trusted source. Read/write.

Syntax

expression .EnableTrustedBrowser

expression An expression that returns a Permission object.

Return Value

Boolean

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.Item Property (Office)

 Copy code hover
[image]

Permission.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a UserPermission object that is a member of the Permission collection. The UserPermission object associates a set of permissions on the active document with a single user and an optional expiration date. Read-only.

Syntax

expression .Item(Index)

expression Required. A variable that represents a Permission object. An item that returns a Permission object.

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.Parent Property (Office)

 Copy code hover
[image]

Permission.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the Permission object. Read-only.

Syntax

expression .Parent

expression A variable that represents a Permission object.

Return Value

Object

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.PermissionFromPolicy Property (Office)

 Copy code hover
[image]

Permission.PermissionFromPolicy Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value that indicates whether a permission policy has been applied to the active document. Read-only.

Syntax

expression .PermissionFromPolicy

expression A variable that represents a Permission object.

Remarks

Information Rights Management in Microsoft Office supports the use of administrative permission policies which list users and groups and their document permissions. The PermissionFromPolicy property returns a Boolean value that indicates whether a permission policy was applied to the active document the last time permissions were enabled on the document.

The PermissionFromPolicy property always returns False when checked by a non-owner of the document, even when the user has object model permissions.

Example

The following example displays permission policy information about the active document.

Copy code Copy code
 Dim irmPermission As Office.Permission
 Dim strIRMInfo As String
 Set irmPermission = ActiveWorkbook.Permission
 If irmPermission.Enabled Then
 strIRMInfo = "Permissions are restricted on this document." & vbCrLf
 If irmPermission.PermissionFromPolicy Then
 strIRMInfo = strIRMInfo & " Permissions applied from policy:" & vbCrLf & _
 " Policy name: " & irmPermission.PolicyName & vbCrLf & _
 " Policy description: " & irmPermission.PolicyDescription
 Else
 strIRMInfo = strIRMInfo & " Default permissions applied." & vbCrLf & _
 " Default policy name: " & irmPermission.PolicyName & vbCrLf & _
 " Default policy description: " & irmPermission.PolicyDescription
 End If
 Else
 strIRMInfo = "Permission are NOT restricted on this document."
 End If
 MsgBox strIRMInfo, vbInformation + vbOKOnly, "IRM Information"
 Set irmPermission = Nothing

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.PolicyDescription Property (Office)

 Copy code hover
[image]

Permission.PolicyDescription Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the description of the permissions policy applied to the active document. Read-only.

Syntax

expression .PolicyDescription

expression A variable that represents a Permission object.

Remarks

Microsoft Office Information Rights Management supports the use of administrative permission policies which list users and groups and their document permissions. The PolicyDescription property returns the description of the policy applied to the active document, or a default value if a policy was not used.

Example

The following example displays permission policy information about the active document.

Copy code Copy code
 Dim irmPermission As Office.Permission
 Dim strIRMInfo As String
 Set irmPermission = ActiveWorkbook.Permission
 If irmPermission.Enabled Then
 strIRMInfo = "Permissions are restricted on this document." & vbCrLf
 If irmPermission.PermissionFromPolicy Then
 strIRMInfo = strIRMInfo & " Permissions applied from policy:" & vbCrLf & _
 " Policy name: " & irmPermission.PolicyName & vbCrLf & _
 " Policy description: " & irmPermission.PolicyDescription
 Else
 strIRMInfo = strIRMInfo & " Default permissions applied." & vbCrLf & _
 " Default policy name: " & irmPermission.PolicyName & vbCrLf & _
 " Default policy description: " & irmPermission.PolicyDescription
 End If
 Else
 strIRMInfo = "Permission are NOT restricted on this document."
 End If
 MsgBox strIRMInfo, vbInformation + vbOKOnly, "IRM Information"
 Set irmPermission = Nothing

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.PolicyName Property (Office)

 Copy code hover
[image]

Permission.PolicyName Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the permissions policy applied to the active document. Read-only.

Syntax

expression .PolicyName

expression A variable that represents a Permission object.

Remarks

Microsoft Office Information Rights Management supports the use of administrative permission policies which list users and groups and their document permissions. The PolicyName property returns the name of the policy applied to the active document, or a default value if a policy was not used.

Example

The following example displays permission policy information about the active document.

Copy code Copy code
 Dim irmPermission As Office.Permission
 Dim strIRMInfo As String
 Set irmPermission = ActiveWorkbook.Permission
 If irmPermission.Enabled Then
 strIRMInfo = "Permissions are restricted on this document." & vbCrLf
 If irmPermission.PermissionFromPolicy Then
 strIRMInfo = strIRMInfo & " Permissions applied from policy:" & vbCrLf & _
 " Policy name: " & irmPermission.PolicyName & vbCrLf & _
 " Policy description: " & irmPermission.PolicyDescription
 Else
 strIRMInfo = strIRMInfo & " Default permissions applied." & vbCrLf & _
 " Default policy name: " & irmPermission.PolicyName & vbCrLf & _
 " Default policy description: " & irmPermission.PolicyDescription
 End If
 Else
 strIRMInfo = "Permission are NOT restricted on this document."
 End If
 MsgBox strIRMInfo, vbInformation + vbOKOnly, "IRM Information"
 Set irmPermission = Nothing

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.RequestPermissionURL Property (Office)

 Copy code hover
[image]

Permission.RequestPermissionURL Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the file or Web site URL to visit or the e-mail address to contact for users who need additional permissions on the active document. Read/write.

Syntax

expression .RequestPermissionURL

expression A variable that represents a Permission object.

Remarks

The RequestPermissionURL setting corresponds to the Users can request additional permissions from option in the permissions user interface. Use the RequestPermissionURL property to specify a file, a Web site, or an e-mail contact from which users can request, or learn how to request, additional permissions on the active document, for example:

  • A Web address: http://companyserver/request_permissions.asp

  • A file: \\companyserver\share\requesting_permissions.txt

  • An email address: mailto:permissionsmgr@example.com?Subject=Request%20permissions

Example

The following example displays information about the permissions settings of the active document, including the RequestPermissionURL setting.

Copy code Copy code
 Dim irmPermission As Office.Permission
 Dim strIRMInfo As String
 Set irmPermission = ActiveWorkbook.Permission
 If irmPermission.Enabled Then
 strIRMInfo = "Permissions are restricted on this document." & vbCrLf
 strIRMInfo = strIRMInfo & " View in trusted browser: " & _
 irmPermission.EnableTrustedBrowser & vbCrLf & _
 " Document author: " & irmPermission.DocumentAuthor & vbCrLf & _
 " Users with permissions: " & irmPermission.Count & vbCrLf & _
 " Cache licenses locally: " & irmPermission.StoreLicenses & vbCrLf & _
 " Request permission URL: " & irmPermission.RequestPermissionURL & vbCrLf
 If irmPermission.PermissionFromPolicy Then
 strIRMInfo = strIRMInfo & " Permissions applied from policy:" & vbCrLf & _
 " Policy name: " & irmPermission.PolicyName & vbCrLf & _
 " Policy description: " & irmPermission.PolicyDescription
 Else
 strIRMInfo = strIRMInfo & " Default permissions applied."
 End If
 Else
 strIRMInfo = "Permissions are NOT restricted on this document."
 End If
 MsgBox strIRMInfo, vbInformation + vbOKOnly, "IRM Information"
 Set irmPermission = Nothing

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.StoreLicenses Property (Office)

 Copy code hover
[image]

Permission.StoreLicenses Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a Boolean value that indicates whether the user's license to view the active document should be cached to allow offline viewing when the user cannot connect to a rights management server. Read/write.

Syntax

expression .StoreLicenses

expression A variable that represents a Permission object.

Remarks

The StoreLicenses property corresponds to (and its value is the opposite of) the Require a connection to verify a user's permission option in the permissions user interface. When StoreLicenses is False, users other than the document owner must connect to the rights management server and acquire the license to work with the document each time they open it when content is protected using the Information Rights Management service provided in Microsoft Office.

Example

The following example displays information about the permissions settings of the active document, including the StoreLicenses setting.

Copy code Copy code
 Dim irmPermission As Office.Permission
 Dim strIRMInfo As String
 Set irmPermission = ActiveWorkbook.Permission
 If irmPermission.Enabled Then
 strIRMInfo = "Permissions are restricted on this document." & vbCrLf
 strIRMInfo = strIRMInfo & " View in trusted browser: " & _
 irmPermission.EnableTrustedBrowser & vbCrLf & _
 " Document author: " & irmPermission.DocumentAuthor & vbCrLf & _
 " Users with permissions: " & irmPermission.Count & vbCrLf & _
 " Cache licenses locally: " & irmPermission.StoreLicenses & vbCrLf & _
 " Request permission URL: " & irmPermission.RequestPermissionURL & vbCrLf
 If irmPermission.PermissionFromPolicy Then
 strIRMInfo = strIRMInfo & " Permissions applied from policy:" & vbCrLf & _
 " Policy name: " & irmPermission.PolicyName & vbCrLf & _
 " Policy description: " & irmPermission.PolicyDescription
 Else
 strIRMInfo = strIRMInfo & " Custom permissions applied."
 End If
 Else
 strIRMInfo = "Permissions are NOT restricted on this document."
 End If
 MsgBox strIRMInfo, vbInformation + vbOKOnly, "IRM Information"
 Set irmPermission = Nothing

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission Methods (Office)

 Copy code hover
[image]

Permission Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Creates a set of permissions on the active document for the specified user. Returns a UserPermission object.
ApplyPolicy | Applies the specified permission policy to the active document.
RemoveAll | Removes all UserPermission objects from the Permission collection of the active document.


Permission.Add Method (Office)

 Copy code hover
[image]

Permission.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Creates a set of permissions on the active document for the specified user. Returns a UserPermission object.

Syntax

expression .Add(UserID, Permission, ExpirationDate)

expression Required. A variable that represents a Permission object.

Parameters

Name | Required/Optional | Data Type | Description
UserID | Required | String | The e-mail address (in the format user@domain.com) of the user to whom permissions on the active document are being granted.
Permission | Optional | msoPermission | The permissions on the active document that are being granted to the specified user.
ExpirationDate | Optional | Date | The expiration date for the permissions that are being granted.

Example

The following example assigns a combination of read and edit permissions on the current document to a user and specifies an expiration date for these document permissions.

VBA Copy code Copy code
 Dim objUserPerm As Office.UserPermission
 Set objUserPerm = ActiveWorkbook.Permission.Add( _
 "user@domain.com", _
 msoPermissionRead + msoPermissionEdit, #12/31/2005#)
 MsgBox "Permissions added for " & _
 objUserPerm.UserId, _
 vbInformation + vbOKOnly, _
 "Permissions Added"
 Set objUserPerm = Nothing

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.ApplyPolicy Method (Office)

 Copy code hover
[image]

Permission.ApplyPolicy Method (Office)
See also Send feedback

Published: July 09, 2012

Applies the specified permission policy to the active document.

Syntax

expression .ApplyPolicy(FileName)

expression A variable that represents a Permission object.

Parameters

Name | Required/Optional | Data Type | Description
FileName | Required | String | The path and filename of the permission policy template file.

Remarks

Microsoft Office Information Rights Management supports the use of administrative permission policies which list users and groups and their document permissions. The ApplyPolicy method applies a permission policy to the active document.

Example

The following example enables permissions on the active document and applies an administrative permission policy.

Copy code Copy code
 Dim irmPermission As Office.Permission
 Set irmPermission = ActiveWorkbook.Permission
 Dim strIRMInfo As String
 Select Case irmPermission.Enabled
 Case True
 strIRMInfo = "Permissions are already restricted on this document."
 Case False
 With irmPermission
 .Enabled = True
 .ApplyPolicy ("\\server\share\permissionpolicy.xml")
 End With
 strIRMInfo = "Permissions are now restricted on this document " & _
 vbCrLf & _
 " and the permission policy has been applied."
 End Select
 MsgBox strIRMInfo, vbInformation + vbOKOnly, "IRM Information"
 Set irmPermission = Nothing

See also

Concepts

Permission Object

Other resources

Permission Object Members


Permission.RemoveAll Method (Office)

 Copy code hover
[image]

Permission.RemoveAll Method (Office)
See also Send feedback

Published: July 09, 2012

Removes all UserPermission objects from the Permission collection of the active document.

Syntax

expression .RemoveAll

expression A variable that represents a Permission object.

Remarks

The RemoveAll method removes all UserPermissions that have been added to the Permission collection and disables restrictions on the active document. After calling the RemoveAll method, the Enabled property of the Permission object returns False and the Count property returns 0 (zero).

Example

The following example uses the RemoveAll method to remove all user permissions and to disable restrictions on the active document.

Copy code Copy code
 Dim irmPermission As Office.Permission
 Set irmPermission = ActiveWorkbook.Permission
 If irmPermission.Enabled Then
 irmPermission.RemoveAll
 MsgBox "All permissions removed." & vbCrLf & _
 "Count: " & irmPermission.Count & vbCrLf & _
 "Enabled: " & irmPermission.Enabled, _
 vbInformation + vbOKOnly, "IRM Information"
 Else
 MsgBox "This document is not restricted.", _
 vbInformation + vbOKOnly, "IRM Information"
 End If
 Set irmPermission = Nothing

See also

Concepts

Permission Object

Other resources

Permission Object Members


PickerDialog Object (Office)

 Copy code hover
[image]

PickerDialog Object (Office)
See also Send feedback

Published: July 09, 2012

Provides dialog user interface functionality of for picking people or picking data.

Version Information

Version Added: Office 2010

Remarks

Get the PickerDialog object through the PickerDialog property in Application object.

Example

The following code sets the Picker Dialog properties and then displays the Picker Dialog.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResult As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

See also

Concepts

Object Model Reference

Other resources

PickerDialog Object Members


PickerDialog Members (Office)

 Copy code hover
[image]

PickerDialog Members (Office)
Send feedback

Published: July 09, 2012

Provides dialog user interface functionality of for picking people or picking data.

Methods

Name | Description
CreatePickerResults | Creates an empty PickerResults object.
Resolve | Resolves the token using the Picker Dialog and retrieves the results.
Show | Displays the Picker Dialog with already specified data handler and given options.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerDialog object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerDialog object was created. Read-only
DataHandlerId | Sets or gets the GUID of the Picker Dialog data handler component. Read/write
Properties | Returns the PickerProperties object to specify custom properties for data handler component. Read-only
Title | Set or returns the title of a picker dialog displayed in the Picker Dialog. Read/write


PickerDialog Properties (Office)

 Copy code hover
[image]

PickerDialog Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerDialog object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerDialog object was created. Read-only
DataHandlerId | Sets or gets the GUID of the Picker Dialog data handler component. Read/write
Properties | Returns the PickerProperties object to specify custom properties for data handler component. Read-only
Title | Set or returns the title of a picker dialog displayed in the Picker Dialog. Read/write


PickerDialog.Application Property (Office)

 Copy code hover
[image]

PickerDialog.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the PickerDialog object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a PickerDialog object.

See also

Concepts

PickerDialog Object

Other resources

PickerDialog Object Members


PickerDialog.Creator Property (Office)

 Copy code hover
[image]

PickerDialog.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the PickerDialog object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a PickerDialog object.

See also

Concepts

PickerDialog Object

Other resources

PickerDialog Object Members


PickerDialog.DataHandlerId Property (Office)

 Copy code hover
[image]

PickerDialog.DataHandlerId Property (Office)
See also Send feedback

Published: July 09, 2012

Sets or gets the GUID of the Picker Dialog data handler component. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .DataHandlerId

expression An expression that returns a PickerDialog object.

Remarks

You must specify DataHandlerID before invoking the Picker Dialog.

Example

The following code sets the Picker Dialog properties and then displays the Picker Dialog.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResult As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

See also

Concepts

PickerDialog Object

Other resources

PickerDialog Object Members


PickerDialog.Properties Property (Office)

 Copy code hover
[image]

PickerDialog.Properties Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the PickerProperties object to specify custom properties for data handler component. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Properties

expression An expression that returns a PickerDialog object.

Remarks

The properties of the PickerProperties object will be passed to the data handler.

Example

The following code sets various Picker Dialog properties and retrieves the results.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties

Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)

' Show the Picker Dialog with no existing result.
Set objPickerResults = objPickerDialog.Show(True)

See also

Concepts

PickerDialog Object

Other resources

PickerDialog Object Members


PickerDialog.Title Property (Office)

 Copy code hover
[image]

PickerDialog.Title Property (Office)
See also Send feedback

Published: July 09, 2012

Set or returns the title of a picker dialog displayed in the Picker Dialog. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Title

expression An expression that returns a PickerDialog object.

Example

The following code sets the Picker Dialog properties and then displays the Picker Dialog.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResult As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

See also

Concepts

PickerDialog Object

Other resources

PickerDialog Object Members


PickerDialog Methods (Office)

 Copy code hover
[image]

PickerDialog Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
CreatePickerResults | Creates an empty PickerResults object.
Resolve | Resolves the token using the Picker Dialog and retrieves the results.
Show | Displays the Picker Dialog with already specified data handler and given options.


PickerDialog.CreatePickerResults Method (Office)

 Copy code hover
[image]

PickerDialog.CreatePickerResults Method (Office)
See also Send feedback

Published: July 09, 2012

Creates an empty PickerResults object.

Version Information

Version Added: Office 2010

Syntax

expression .CreatePickerResults

expression An expression that returns a PickerDialog object.

Return Value

PickerResults

Remarks

You can add the PickerResult to the returned object and specify it to the second parameter of the Show method as already existing results of the PickerDialog object.

Example

The following code sets various properties of the Picker Dialog and adds the already existing PickerResults to the results.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerExistingResults As PickerResults

Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"

Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

See also

Concepts

PickerDialog Object

Other resources

PickerDialog Object Members


PickerDialog.Resolve Method (Office)

 Copy code hover
[image]

PickerDialog.Resolve Method (Office)
See also Send feedback

Published: July 09, 2012

Resolves the token using the Picker Dialog and retrieves the results.

Version Information

Version Added: Office 2010

Syntax

expression .Resolve(TokenText, duplicateDlgMode)

expression An expression that returns a PickerDialog object.

Parameters

Name | Required/Optional | Data Type | Description
TokenText | Required | String | The text string to resolve.
duplicateDlgMode | Required | Integer |

Return Value

PickerResults

Example

Resolves entities by using the Picker Dialog object.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResult As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)

' Resolve the token by using Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Resolve("johndoe", False)

See also

Concepts

PickerDialog Object

Other resources

PickerDialog Object Members


PickerDialog.Show Method (Office)

 Copy code hover
[image]

PickerDialog.Show Method (Office)
See also Send feedback

Published: July 09, 2012

Displays the Picker Dialog with already specified data handler and given options.

Version Information

Version Added: Office 2010

Syntax

expression .Show(IsMultiSelect, ExistingResults)

expression An expression that returns a PickerDialog object.

Parameters

Name | Required/Optional | Data Type | Description
IsMultiSelect | Optional | Boolean | Specifies whether the Picker Dialog user interface provides multiple item selection functions.
ExistingResults | Optional | PickerResults | Contains existing PickerResults in Picker Dialog user interface. These results are displayed in the selected item control.

Return Value

PickerResults

Example

The following code sets the Picker Dialog properties and then displays the Picker Dialog.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResult As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

See also

Concepts

PickerDialog Object

Other resources

PickerDialog Object Members


PickerField Object (Office)

 Copy code hover
[image]

PickerField Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the field definitions of sub-items in a PickerResult object. Each PickerField object represents a column definition of a Picker dialog.

Version Information

Version Added: Office 2010

See also

Concepts

Object Model Reference

Other resources

PickerField Object Members


PickerField Members (Office)

 Copy code hover
[image]

PickerField Members (Office)
Send feedback

Published: July 09, 2012

Represents the field definitions of sub-items in a PickerResult object. Each PickerField object represents a column definition of a Picker dialog.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerField object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerField object was created. Read-only
IsHidden | Specifies whether the Picker field is hidden. Read-only
Name | Retrieves the name of the Picker field. Read-only
Type | The type of the Picker field. Read-only


PickerField Properties (Office)

 Copy code hover
[image]

PickerField Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerField object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerField object was created. Read-only
IsHidden | Specifies whether the Picker field is hidden. Read-only
Name | Retrieves the name of the Picker field. Read-only
Type | The type of the Picker field. Read-only


PickerField.Application Property (Office)

 Copy code hover
[image]

PickerField.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the PickerField object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a PickerField object.

See also

Concepts

PickerField Object

Other resources

PickerField Object Members


PickerField.Creator Property (Office)

 Copy code hover
[image]

PickerField.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the PickerField object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a PickerField object.

See also

Concepts

PickerField Object

Other resources

PickerField Object Members


PickerField.IsHidden Property (Office)

 Copy code hover
[image]

PickerField.IsHidden Property (Office)
See also Send feedback

Published: July 09, 2012

Specifies whether the Picker field is hidden. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .IsHidden

expression An expression that returns a PickerField object.

See also

Concepts

PickerField Object

Other resources

PickerField Object Members


PickerField.Name Property (Office)

 Copy code hover
[image]

PickerField.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the name of the Picker field. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Name

expression An expression that returns a PickerField object.

See also

Concepts

PickerField Object

Other resources

PickerField Object Members


PickerField.Type Property (Office)

 Copy code hover
[image]

PickerField.Type Property (Office)
See also Send feedback

Published: July 09, 2012

The type of the Picker field. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Type

expression An expression that returns a PickerField object.

See also

Concepts

PickerField Object

Other resources

PickerField Object Members


PickerFields Object (Office)

 Copy code hover
[image]

PickerFields Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of PickerField objects. Each PickerField object represents a column definition of Picker dialog.

Version Information

Version Added: Office 2010

See also

Concepts

Object Model Reference

Other resources

PickerFields Object Members


PickerFields Members (Office)

 Copy code hover
[image]

PickerFields Members (Office)
Send feedback

Published: July 09, 2012

A collection of PickerField objects. Each PickerField object represents a column definition of Picker dialog.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerFields object. Read-only
Count | Retrieves the count of the number of PickerField objects contained within the PickerFields collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerFields object was created. Read-only
Item | Retrieves a PickerField object at the specified index. Read-only


PickerFields Properties (Office)

 Copy code hover
[image]

PickerFields Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerFields object. Read-only
Count | Retrieves the count of the number of PickerField objects contained within the PickerFields collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerFields object was created. Read-only
Item | Retrieves a PickerField object at the specified index. Read-only


PickerFields.Application Property (Office)

 Copy code hover
[image]

PickerFields.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the PickerFields object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a PickerFields object.

See also

Concepts

PickerFields Object

Other resources

PickerFields Object Members


PickerFields.Count Property (Office)

 Copy code hover
[image]

PickerFields.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the count of the number of PickerField objects contained within the PickerFields collection. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Count

expression An expression that returns a PickerFields object.

See also

Concepts

PickerFields Object

Other resources

PickerFields Object Members


PickerFields.Creator Property (Office)

 Copy code hover
[image]

PickerFields.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the PickerFields object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a PickerFields object.

See also

Concepts

PickerFields Object

Other resources

PickerFields Object Members


PickerFields.Item Property (Office)

 Copy code hover
[image]

PickerFields.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves a PickerField object at the specified index. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Item(Index)

expression An expression that returns a PickerFields object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Integer | Specifies an integer representing the index of the PickerField.

See also

Concepts

PickerFields Object

Other resources

PickerFields Object Members


PickerProperties Object (Office)

 Copy code hover
[image]

PickerProperties Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of PickerProperty objects.

Version Information

Version Added: Office 2010

Remarks

Each PickerProperty object is a Name(ID)/Value pair for passing option values to a PickerDialog object. You can get a PickerProperties collection object through the Properties property of PickerDialog object.

Example

The following code sets the Picker Dialog properties and then displays the Picker Dialog.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResult As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

See also

Concepts

Object Model Reference

Other resources

PickerProperties Object Members


PickerProperties Members (Office)

 Copy code hover
[image]

PickerProperties Members (Office)
Send feedback

Published: July 09, 2012

A collection of PickerProperty objects.

Methods

Name | Description
Add |
Remove | Removes a PickerProperty from the collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerProperties object. Read-only
Count | Retrieves the count of the number of PickerProperty objects contained within the PickerProperties collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerProperties object was created. Read-only
Item | Retrieves a PickerProperty object at the specified index. Read-only


PickerProperties Properties (Office)

 Copy code hover
[image]

PickerProperties Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerProperties object. Read-only
Count | Retrieves the count of the number of PickerProperty objects contained within the PickerProperties collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerProperties object was created. Read-only
Item | Retrieves a PickerProperty object at the specified index. Read-only


PickerProperties.Application Property (Office)

 Copy code hover
[image]

PickerProperties.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the PickerProperties object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a PickerProperties object.

See also

Concepts

PickerProperties Object

Other resources

PickerProperties Object Members


PickerProperties.Count Property (Office)

 Copy code hover
[image]

PickerProperties.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the count of the number of PickerProperty objects contained within the PickerProperties collection. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Count

expression An expression that returns a PickerProperties object.

See also

Concepts

PickerProperties Object

Other resources

PickerProperties Object Members


PickerProperties.Creator Property (Office)

 Copy code hover
[image]

PickerProperties.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the PickerProperties object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a PickerProperties object.

See also

Concepts

PickerProperties Object

Other resources

PickerProperties Object Members


PickerProperties.Item Property (Office)

 Copy code hover
[image]

PickerProperties.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves a PickerProperty object at the specified index. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Item(Index)

expression An expression that returns a PickerProperties object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Integer | Specifies an integer representing the index of the PickerProperty object.

See also

Concepts

PickerProperties Object

Other resources

PickerProperties Object Members


PickerProperties Methods (Office)

 Copy code hover
[image]

PickerProperties Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add |
Remove | Removes a PickerProperty from the collection.


PickerProperties.Add Method (Office)

 Copy code hover
[image]

PickerProperties.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Version Information

Version Added: Office 2010

Syntax

expression .Add(Id, Value, Type)

expression An expression that returns a PickerProperties object.

Parameters

Name | Required/Optional | Data Type | Description
Id | Required | String | Key name of the property.
Value | Required | String | Value of the property.
Type | Required | MsoPickerField | Type of the property.

Return Value

PickerProperty

Example

The following code sets various properties of the PickerDialog object.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties

' Configure Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)

See also

Concepts

PickerProperties Object

Other resources

PickerProperties Object Members


PickerProperties.Remove Method (Office)

 Copy code hover
[image]

PickerProperties.Remove Method (Office)
See also Send feedback

Published: July 09, 2012

Removes a PickerProperty from the collection.

Version Information

Version Added: Office 2010

Syntax

expression .Remove(Id)

expression An expression that returns a PickerProperties object.

Parameters

Name | Required/Optional | Data Type | Description
Id | Required | String | The identifier of the PickerProperty to remove.

Return Value

Nothing

See also

Concepts

PickerProperties Object

Other resources

PickerProperties Object Members


PickerProperty Object (Office)

 Copy code hover
[image]

PickerProperty Object (Office)
See also Send feedback

Published: July 09, 2012

Represents an object for passing a custom property. p

Version Information

Version Added: Office 2010

Example

The following code sets the Picker Dialog properties and then displays the Picker dialog.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResult As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

See also

Concepts

Object Model Reference

Other resources

PickerProperty Object Members


PickerProperty Members (Office)

 Copy code hover
[image]

PickerProperty Members (Office)
Send feedback

Published: July 09, 2012

Represents an object for passing a custom property. p

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerProperty object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerProperty object was created. Read-only
Id | Retrieves the unique Id of the associated PickerProperty object. Read-only
Type | Retrieves the type of the Picker property. Read-only
Value | Retrieves the value of a Picker property. Read-only


PickerProperty Properties (Office)

 Copy code hover
[image]

PickerProperty Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerProperty object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerProperty object was created. Read-only
Id | Retrieves the unique Id of the associated PickerProperty object. Read-only
Type | Retrieves the type of the Picker property. Read-only
Value | Retrieves the value of a Picker property. Read-only


PickerProperty.Application Property (Office)

 Copy code hover
[image]

PickerProperty.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the PickerProperty object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a PickerProperty object.

See also

Concepts

PickerProperty Object

Other resources

PickerProperty Object Members


PickerProperty.Creator Property (Office)

 Copy code hover
[image]

PickerProperty.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the PickerProperty object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a PickerProperty object.

See also

Concepts

PickerProperty Object

Other resources

PickerProperty Object Members


PickerProperty.Id Property (Office)

 Copy code hover
[image]

PickerProperty.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the unique Id of the associated PickerProperty object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Id

expression An expression that returns a PickerProperty object.

See also

Concepts

PickerProperty Object

Other resources

PickerProperty Object Members


PickerProperty.Type Property (Office)

 Copy code hover
[image]

PickerProperty.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the type of the Picker property. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Type

expression An expression that returns a PickerProperty object.

See also

Concepts

PickerProperty Object

Other resources

PickerProperty Object Members


PickerProperty.Value Property (Office)

 Copy code hover
[image]

PickerProperty.Value Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the value of a Picker property. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Value

expression An expression that returns a PickerProperty object.

See also

Concepts

PickerProperty Object

Other resources

PickerProperty Object Members


PickerResult Object (Office)

 Copy code hover
[image]

PickerResult Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a resolved or selected item of data.

Version Information

Version Added: Office 2010

Example

The following code sets the Picker Dialog properties and then displays the Picker dialog.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResult As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

See also

Concepts

Object Model Reference

Other resources

PickerResult Object Members


PickerResult Members (Office)

 Copy code hover
[image]

PickerResult Members (Office)
Send feedback

Published: July 09, 2012

Represents a resolved or selected item of data.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerResult object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerResult object was created. Read-only
DisplayName | Represents a display name of PickerResult. Read/write
DuplicateResults | Gets PickerResult collection if the result of resolving results has multiple candidates. Read-only
Fields | Represent field definitions of SubItems in a PickerFields collection. Read-only
Id | Retrieves the unique Id of the associated PickerResult object. Read-only
ItemData | Gets or sets a non-display purpose item binding to data. Read/write
SIPId | Is the identifier for Office Communication Server. It's used only for people picking scenario. Read/write
SubItems | Display purpose or non-display purpose field data of a PickerResult object. It is used for passing column values in a Picker dialog. Read/write
Type | Represents the type of a PickerResult object. Read/write


PickerResult Properties (Office)

 Copy code hover
[image]

PickerResult Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerResult object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerResult object was created. Read-only
DisplayName | Represents a display name of PickerResult. Read/write
DuplicateResults | Gets PickerResult collection if the result of resolving results has multiple candidates. Read-only
Fields | Represent field definitions of SubItems in a PickerFields collection. Read-only
Id | Retrieves the unique Id of the associated PickerResult object. Read-only
ItemData | Gets or sets a non-display purpose item binding to data. Read/write
SIPId | Is the identifier for Office Communication Server. It's used only for people picking scenario. Read/write
SubItems | Display purpose or non-display purpose field data of a PickerResult object. It is used for passing column values in a Picker dialog. Read/write
Type | Represents the type of a PickerResult object. Read/write


PickerResult.Application Property (Office)

 Copy code hover
[image]

PickerResult.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the PickerResult object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a PickerResult object.

See also

Concepts

PickerResult Object

Other resources

PickerResult Object Members


PickerResult.Creator Property (Office)

 Copy code hover
[image]

PickerResult.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the PickerResult object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a PickerResult object.

See also

Concepts

PickerResult Object

Other resources

PickerResult Object Members


PickerResult.DisplayName Property (Office)

 Copy code hover
[image]

PickerResult.DisplayName Property (Office)
See also Send feedback

Published: July 09, 2012

Represents a display name of PickerResult. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .DisplayName

expression An expression that returns a PickerResult object.

See also

Concepts

PickerResult Object

Other resources

PickerResult Object Members


PickerResult.DuplicateResults Property (Office)

 Copy code hover
[image]

PickerResult.DuplicateResults Property (Office)
See also Send feedback

Published: July 09, 2012

Gets PickerResult collection if the result of resolving results has multiple candidates. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .DuplicateResults

expression An expression that returns a PickerResult object.

See also

Concepts

PickerResult Object

Other resources

PickerResult Object Members


PickerResult.Fields Property (Office)

 Copy code hover
[image]

PickerResult.Fields Property (Office)
See also Send feedback

Published: July 09, 2012

Represent field definitions of SubItems in a PickerFields collection. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Fields

expression An expression that returns a PickerResult object.

See also

Concepts

PickerResult Object

Other resources

PickerResult Object Members


PickerResult.Id Property (Office)

 Copy code hover
[image]

PickerResult.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the unique Id of the associated PickerResult object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Id

expression An expression that returns a PickerResult object.

See also

Concepts

PickerResult Object

Other resources

PickerResult Object Members


PickerResult.ItemData Property (Office)

 Copy code hover
[image]

PickerResult.ItemData Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a non-display purpose item binding to data. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .ItemData

expression An expression that returns a PickerResult object.

See also

Concepts

PickerResult Object

Other resources

PickerResult Object Members


PickerResult.SIPId Property (Office)

 Copy code hover
[image]

PickerResult.SIPId Property (Office)
See also Send feedback

Published: July 09, 2012

Is the identifier for Office Communication Server. It's used only for people picking scenario. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .SIPId

expression An expression that returns a PickerResult object.

See also

Concepts

PickerResult Object

Other resources

PickerResult Object Members


PickerResult.SubItems Property (Office)

 Copy code hover
[image]

PickerResult.SubItems Property (Office)
See also Send feedback

Published: July 09, 2012

Display purpose or non-display purpose field data of a PickerResult object. It is used for passing column values in a Picker dialog. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .SubItems

expression An expression that returns a PickerResult object.

See also

Concepts

PickerResult Object

Other resources

PickerResult Object Members


PickerResult.Type Property (Office)

 Copy code hover
[image]

PickerResult.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Represents the type of a PickerResult object. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Type

expression An expression that returns a PickerResult object.

Example

The following code sets the Picker Dialog properties and then displays the Picker Dialog.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResult As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

See also

Concepts

PickerResult Object

Other resources

PickerResult Object Members


PickerResults Object (Office)

 Copy code hover
[image]

PickerResults Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of PickerResult objects.

Version Information

Version Added: Office 2010

Remarks

Each PickerResult object represents a resolved or selected item data.

Example

The following code displays the Picker Dialog, gets results, and then enumerates those results.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResults As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

' Enumerate the results.
For index = 1 To objPickerResults.Count-1
 Debug.Print objPickerResults.Item(index).Id
 Debug.Print objPickerResults.Item(index).DisplayName
 Debug.Print objPickerResults.Item(index).Type
 Debug.Print objPickerResults.Item(index).SIPId
Next

See also

Concepts

Object Model Reference

Other resources

PickerResults Object Members


PickerResults Members (Office)

 Copy code hover
[image]

PickerResults Members (Office)
Send feedback

Published: July 09, 2012

A collection of PickerResult objects.

Methods

Name | Description
Add | Adds a PickerResult object to the PickerResults collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerResults object. Read-only
Count | Retrieves the count of the number of PickerResult objects contained within the PickerResults collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerResults object was created. Read-only
Item | Retrieves a PickerResult object at the specified index. Read-only


PickerResults Properties (Office)

 Copy code hover
[image]

PickerResults Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PickerResults object. Read-only
Count | Retrieves the count of the number of PickerResult objects contained within the PickerResults collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PickerResults object was created. Read-only
Item | Retrieves a PickerResult object at the specified index. Read-only


PickerResults.Application Property (Office)

 Copy code hover
[image]

PickerResults.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the PickerResults object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a PickerResults object.

See also

Concepts

PickerResults Object

Other resources

PickerResults Object Members


PickerResults.Count Property (Office)

 Copy code hover
[image]

PickerResults.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the count of the number of PickerResult objects contained within the PickerResults collection. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Count

expression An expression that returns a PickerResults object.

Example

The following code displays the Picker Dialog user interface, gets results, and then enumerates those results.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResults As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

' Enumerate the results.
For index = 1 To objPickerResults.Count-1
 Debug.Print objPickerResults.Item(index).Id
 Debug.Print objPickerResults.Item(index).DisplayName
 Debug.Print objPickerResults.Item(index).Type
 Debug.Print objPickerResults.Item(index).SIPId
Next

See also

Concepts

PickerResults Object

Other resources

PickerResults Object Members


PickerResults.Creator Property (Office)

 Copy code hover
[image]

PickerResults.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the PickerResults object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a PickerResults object.

See also

Concepts

PickerResults Object

Other resources

PickerResults Object Members


PickerResults.Item Property (Office)

 Copy code hover
[image]

PickerResults.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves a PickerResult object at the specified index. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Item(Index)

expression An expression that returns a PickerResults object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Integer | Specifies an integer representing the indexed location of the PickerResult object.

Example

The following code displays the Picker Dialog user interface, gets results, and then enumerates those results.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResults As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

' Enumerate the results.
For index = 1 To objPickerResults.Count-1
 Debug.Print objPickerResults.Item(index).Id
 Debug.Print objPickerResults.Item(index).DisplayName
 Debug.Print objPickerResults.Item(index).Type
 Debug.Print objPickerResults.Item(index).SIPId
Next

See also

Concepts

PickerResults Object

Other resources

PickerResults Object Members


PickerResults Methods (Office)

 Copy code hover
[image]

PickerResults Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a PickerResult object to the PickerResults collection.


PickerResults.Add Method (Office)

 Copy code hover
[image]

PickerResults.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a PickerResult object to the PickerResults collection.

Version Information

Version Added: Outlook 2010

Syntax

expression .Add(Id, DisplayName, Type, SIPId, ItemData, SubItems)

expression An expression that returns a PickerResults object.

Parameters

Name | Required/Optional | Data Type | Description
Id | Required | String | Represents an identifier of the PickerResult.
DisplayName | Required | String | Represents a display name of the PickerResult.
Type | Required | String | Represents a type of the PickerResult.
SIPId | Optional | String | Currently not supported. The SIPId is the identifier for Office Communication Server. It is used only for the people picking scenario.
ItemData | Optional | Variant | Non- displaying item binding data
SubItems | Optional | Variant | Displays the purpose or non-display purpose field data of the PickerResult. It is used for passing column values in the Picker Dialog.

Return Value

PickerResult

Example

The following code sets the Picker Dialog properties and then displays the Picker Dialog.

VBA Copy code Copy code
Dim objPickerDialog As PickerDialog
Dim objPickerProperties As PickerProperties
Dim objPickerProperty As PickerProperty
Dim objPickerExistingResults As PickerResults
Dim objPickerExistingResults As PickerResult
Dim objPickerResults As PickerResults

' Configure the Picker Dialog properties.
Set objPickerDialog = Application.PickerDialog
objPickerDialog.DataHandlerId = "{000CDF0A-0000-0000-C000-000000000046}"
objPickerDialog.Title = "Sample Picker Dialog"
Set objPickerProperties = objPickerDialog.Properties
Set objPickerProperty = objPickerProperties.Add("SiteUrl", "http://my", msoPickerFieldtypeText)
Set objPickerExistingResults = objPickerDialog.CreatePickerResults
Set objPickerExistingResult = objPickerExistingResults.Add("johndoe@contoso.com", "John Doe", "User")

' Show the Picker Dialog and get the results.
Set objPickerResults = objPickerDialog.Show(True, objPickerExistingResult)

See also

Concepts

PickerResults Object

Other resources

PickerResults Object Members


PictureEffect Object (Office)

 Copy code hover
[image]

PictureEffect Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a Picture Effect.

Version Information

Version Added: Office 2010

Remarks

Picture Effects are processed as a chain composed of individual items which are applied in sequence to create the final composited image. An Effects chain will allow an effect to be added to the chain, reordered, or removed from the chain.

Example

The following code sets several Picture Effect fill properties on a shape in a Microsoft PowerPoint slide.

VBA Copy code Copy code
Sub PictureEffectSample()
' Setup a slide with one picture shape.
With ActivePresentation.Slides(1).Shapes(1).Fill.PictureEffects

 ' Insert a 150% Saturation effect.
 .Insert(msoEffectSaturation).EffectParameters(1).Value = 1.5

 ' Insert Brightness/Contrast effect and set values to -50% Brightness and +25% Contrast.
 Dim brightnessContrast As PictureEffect
 Set brightnessContrast = .Insert(msoEffectBrightnessContrast)
 brightnessContrast.EffectParameters(1).Value = -0.5
 brightnessContrast.EffectParameters(2).Value = 0.25

 ' Remove all Picture effects.
 While .Count > 0
 .Delete (1)
 Wend

End With
End Sub

See also

Concepts

Object Model Reference

Other resources

PictureEffect Object Members


PictureEffect Members (Office)

 Copy code hover
[image]

PictureEffect Members (Office)
Send feedback

Published: July 09, 2012

Represents a Picture Effect.

Methods

Name | Description
Delete | Deletes a Picture Effect.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PictureEffect object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PictureEffect object was created. Read-only
EffectParameters | Returns an EffectParameter object. Read-only
Position | Specifies the position of a Picture Effect in a chain of composite effects. Read/write
Type | Specifies the type of Picture Effect. Read-only
Visible | Gets or sets a Boolean value representing the visible state of the picture effect. Read/write


PictureEffect Properties (Office)

 Copy code hover
[image]

PictureEffect Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PictureEffect object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PictureEffect object was created. Read-only
EffectParameters | Returns an EffectParameter object. Read-only
Position | Specifies the position of a Picture Effect in a chain of composite effects. Read/write
Type | Specifies the type of Picture Effect. Read-only
Visible | Gets or sets a Boolean value representing the visible state of the picture effect. Read/write


PictureEffect.Application Property (Office)

 Copy code hover
[image]

PictureEffect.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the PictureEffect object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a PictureEffect object.

See also

Concepts

PictureEffect Object

Other resources

PictureEffect Object Members


PictureEffect.Creator Property (Office)

 Copy code hover
[image]

PictureEffect.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the PictureEffect object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a PictureEffect object.

See also

Concepts

PictureEffect Object

Other resources

PictureEffect Object Members


PictureEffect.EffectParameters Property (Office)

 Copy code hover
[image]

PictureEffect.EffectParameters Property (Office)
See also Send feedback

Published: July 09, 2012

Returns an EffectParameter object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .EffectParameters

expression An expression that returns a PictureEffect object.

Remarks

Picture Effects are processed as a chain composed of individual items which are applied in sequence to create the final composited image. An Effects chain will allow an effect to be added to the chain, reordered, or removed from the chain. Effect Parameters specify properties of those effects.

Example

The following code sets several Picture Effect fill properties on a shape in a Microsoft PowerPoint slide.

VBA Copy code Copy code
Sub PictureEffectSample()
' Setup a slide with one picture shape.
With ActivePresentation.Slides(1).Shapes(1).Fill.PictureEffects

 ' Insert a 150% Saturation effect.
 .Insert(msoEffectSaturation).EffectParameters(1).Value = 1.5

 ' Insert Brightness/Contrast effect and set values to -50% Brightness and +25% Contrast.
 Dim brightnessContrast As PictureEffect
 Set brightnessContrast = .Insert(msoEffectBrightnessContrast)
 brightnessContrast.EffectParameters(1).Value = -0.5
 brightnessContrast.EffectParameters(2).Value = 0.25

 ' Remove all Picture effects.
 While .Count > 0
 .Delete (1)
 Wend

End With
End Sub

See also

Concepts

PictureEffect Object

Other resources

PictureEffect Object Members


PictureEffect.Position Property (Office)

 Copy code hover
[image]

PictureEffect.Position Property (Office)
See also Send feedback

Published: July 09, 2012

Specifies the position of a Picture Effect in a chain of composite effects. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Position

expression An expression that returns a PictureEffect object.

Remarks

Picture Effects are processed as a chain composed of individual items which are applied in sequence to create the final composited image. An Effects chain will allow an effect to be added to the chain, reordered, or removed from the chain.

Example

The following code sets several Picture Effect fill properties on a shape in a Microsoft PowerPoint slide.

VBA Copy code Copy code
Sub PictureEffectSample()
' Setup a slide with one picture shape.
With ActivePresentation.Slides(1).Shapes(1).Fill.PictureEffects

 ' Insert a 150% Saturation effect.
 .Insert(msoEffectSaturation).EffectParameters(1).Value = 1.5

 ' Insert Brightness/Contrast effect and set values to -50% Brightness and +25% Contrast.
 Dim brightnessContrast As PictureEffect
 Set brightnessContrast = .Insert(msoEffectBrightnessContrast)
 brightnessContrast.EffectParameters(1).Value = -0.5
 brightnessContrast.EffectParameters(2).Value = 0.25

 ' Remove all Picture effects.
 While .Count > 0
 .Delete (1)
 Wend

End With
End Sub

See also

Concepts

PictureEffect Object

Other resources

PictureEffect Object Members


PictureEffect.Type Property (Office)

 Copy code hover
[image]

PictureEffect.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Specifies the type of Picture Effect. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Type

expression An expression that returns a PictureEffect object.

Remarks

This property takes a MsoPictureEffectType enumeration.

See also

Concepts

PictureEffect Object

Other resources

PictureEffect Object Members


PictureEffect.Visible Property (Office)

 Copy code hover
[image]

PictureEffect.Visible Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a Boolean value representing the visible state of the picture effect. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Visible

expression An expression that returns a PictureEffect object.

See also

Concepts

PictureEffect Object

Other resources

PictureEffect Object Members


PictureEffect Methods (Office)

 Copy code hover
[image]

PictureEffect Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes a Picture Effect.


PictureEffect.Delete Method (Office)

 Copy code hover
[image]

PictureEffect.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes a Picture Effect.

Version Information

Version Added: Office 2010

Syntax

expression .Delete

expression An expression that returns a PictureEffect object.

Return Value

Nothing

See also

Concepts

PictureEffect Object

Other resources

PictureEffect Object Members


PictureEffects Object (Office)

 Copy code hover
[image]

PictureEffects Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of PictureEffects objects.

Version Information

Version Added: Office 2010

Remarks

Picture Effects are processed as a chain composed of individual items which are applied in sequence to create the final composited image. An Effects chain will allow an effect to be added to the chain, reordered, or removed from the chain.

Example

The following code sets several Picture Effect fill properties on a shape in a Microsoft PowerPoint slide.

VBA Copy code Copy code
Sub PictureEffectSample()
' Setup a slide with one picture shape.
With ActivePresentation.Slides(1).Shapes(1).Fill.PictureEffects

 ' Insert a 150% Saturation effect.
 .Insert(msoEffectSaturation).EffectParameters(1).Value = 1.5

 ' Insert Brightness/Contrast effect and set values to -50% Brightness and +25% Contrast.
 Dim brightnessContrast As PictureEffect
 Set brightnessContrast = .Insert(msoEffectBrightnessContrast)
 brightnessContrast.EffectParameters(1).Value = -0.5
 brightnessContrast.EffectParameters(2).Value = 0.25

 ' Remove all Picture effects.
 While .Count > 0
 .Delete (1)
 Wend

End With
End Sub

See also

Concepts

Object Model Reference

Other resources

PictureEffects Object Members


PictureEffects Members (Office)

 Copy code hover
[image]

PictureEffects Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of PictureEffects objects.

Methods

Name | Description
Delete | Deletes a PictureEffect object from the collection.
Insert | Inserts a Picture Effect in a chain of composite effects.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PictureEffects object. Read-only
Count | Retrieves the count of the number of PictureEffect objects contained within the PictureEffects collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PictureEffects object was created. Read-only
Item | Retrieves a PictureEffect object at the specified index. Read-only


PictureEffects Properties (Office)

 Copy code hover
[image]

PictureEffects Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PictureEffects object. Read-only
Count | Retrieves the count of the number of PictureEffect objects contained within the PictureEffects collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the PictureEffects object was created. Read-only
Item | Retrieves a PictureEffect object at the specified index. Read-only


PictureEffects.Application Property (Office)

 Copy code hover
[image]

PictureEffects.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the PictureEffects object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a PictureEffects object.

See also

Concepts

PictureEffects Object

Other resources

PictureEffects Object Members


PictureEffects.Count Property (Office)

 Copy code hover
[image]

PictureEffects.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the count of the number of PictureEffect objects contained within the PictureEffects collection. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Count

expression An expression that returns a PictureEffects object.

See also

Concepts

PictureEffects Object

Other resources

PictureEffects Object Members


PictureEffects.Creator Property (Office)

 Copy code hover
[image]

PictureEffects.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the PictureEffects object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a PictureEffects object.

See also

Concepts

PictureEffects Object

Other resources

PictureEffects Object Members


PictureEffects.Item Property (Office)

 Copy code hover
[image]

PictureEffects.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves a PictureEffect object at the specified index. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Item(Index)

expression An expression that returns a PictureEffects object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Integer | Specifies an integer representing the indexed location of the PictureEffect object.

See also

Concepts

PictureEffects Object

Other resources

PictureEffects Object Members


PictureEffects Methods (Office)

 Copy code hover
[image]

PictureEffects Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes a PictureEffect object from the collection.
Insert | Inserts a Picture Effect in a chain of composite effects.


PictureEffects.Delete Method (Office)

 Copy code hover
[image]

PictureEffects.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes a PictureEffect object from the collection.

Version Information

Version Added: Office 2010

Syntax

expression .Delete(Index)

expression An expression that returns a PictureEffects object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Optional | Integer | The index number of the PictureEffect object to delete.

Return Value

Nothing

See also

Concepts

PictureEffects Object

Other resources

PictureEffects Object Members


PictureEffects.Insert Method (Office)

 Copy code hover
[image]

PictureEffects.Insert Method (Office)
See also Send feedback

Published: July 09, 2012

Inserts a Picture Effect in a chain of composite effects.

Version Information

Version Added: Office 2010

Syntax

expression .Insert(EffectType, Position)

expression An expression that returns a PictureEffects object.

Parameters

Name | Required/Optional | Data Type | Description
EffectType | Required | MsoPictureEffectType | An enumeration specifying the type of Picture Effect.
Position | Optional | Integer | The position of the effect in the composite chain of Picture Effects.

Return Value

PictureEffect

Remarks

Picture Effects are processed as a chain composed of individual items which are applied in sequence to create the final composited image. An Effects chain will allow an effect to be added to the chain, reordered, or removed from the chain.

Example

The following code sets several Picture Effect fill properties on a shape in a Microsoft PowerPoint slide.

VBA Copy code Copy code
Sub PictureEffectSample()
' Setup a slide with one picture shape.
With ActivePresentation.Slides(1).Shapes(1).Fill.PictureEffects

 ' Insert a 150% Saturation effect.
 .Insert(msoEffectSaturation).EffectParameters(1).Value = 1.5

 ' Insert Brightness/Contrast effect and set values to -50% Brightness and +25% Contrast.
 Dim brightnessContrast As PictureEffect
 Set brightnessContrast = .Insert(msoEffectBrightnessContrast)
 brightnessContrast.EffectParameters(1).Value = -0.5
 brightnessContrast.EffectParameters(2).Value = 0.25

 ' Remove all Picture effects.
 While .Count > 0
 .Delete (1)
 Wend

End With
End Sub

See also

Concepts

PictureEffects Object

Other resources

PictureEffects Object Members


PolicyItem Object (Office)

 Copy code hover
[image]

PolicyItem Object (Office)
See also Send feedback

Published: July 09, 2012

Represents an item within a ServerPolicy object that contains the settings for one policy.

Remarks

A policy item cannot exist outside the scope of a policy. Policy items are distinct conditions defined for a document stored on a server running Microsoft Office SharePoint Server.

Example

The following example lists the name and description of all of the policy items for the active document.

VBA Copy code Copy code
Sub ListPolicyItems()
Dim objSrvPolicy As ServerPolicy
Dim objPolicyItem As PolicyItem
Dim strPolicyItemList As String

Set objSrvPolicy = ActiveDocument.ServerPolicy

For Each objPolicyItem In objSrvPolicy
 strPolicyItemList = "Policy Item " & objPolicyItem.Name & " - " & _
 objPolicyItem.Description & vbCrLf
Next
MsgBox (strPolicyItemList)

End Sub

See also

Concepts

Object Model Reference

Other resources

PolicyItem Object Members


PolicyItem Members (Office)

 Copy code hover
[image]

PolicyItem Members (Office)
Send feedback

Published: July 09, 2012

Represents an item within a ServerPolicy object that contains the settings for one policy.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PolicyItem object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the PolicyItem object was created. Read-only.
Data | Gets the information that is used to implement the policy item. Read-only.
Description | Gets a description of the current state of the policy item. Read-only.
Id | Gets the ID of a policy item. PolicyItem objects are contained in ServerPolicy objects. Read-only.
Name | Gets the name of the PolicyItem object. Read-only.
Parent | Gets the Parent object for the PolicyItem object. Read-only.


PolicyItem Properties (Office)

 Copy code hover
[image]

PolicyItem Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the PolicyItem object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the PolicyItem object was created. Read-only.
Data | Gets the information that is used to implement the policy item. Read-only.
Description | Gets a description of the current state of the policy item. Read-only.
Id | Gets the ID of a policy item. PolicyItem objects are contained in ServerPolicy objects. Read-only.
Name | Gets the name of the PolicyItem object. Read-only.
Parent | Gets the Parent object for the PolicyItem object. Read-only.


PolicyItem.Application Property (Office)

 Copy code hover
[image]

PolicyItem.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the PolicyItem object. Read-only.

Syntax

expression .Application

expression An expression that returns a PolicyItem object.

Return Value

Object

See also

Concepts

PolicyItem Object

Other resources

PolicyItem Object Members


PolicyItem.Creator Property (Office)

 Copy code hover
[image]

PolicyItem.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the PolicyItem object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a PolicyItem object.

Return Value

Long

See also

Concepts

PolicyItem Object

Other resources

PolicyItem Object Members


PolicyItem.Data Property (Office)

 Copy code hover
[image]

PolicyItem.Data Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the information that is used to implement the policy item. Read-only.

Syntax

expression .Data

expression An expression that returns a PolicyItem object.

Return Value

String

Remarks

For example, the policy item might contain code to transform the document into a different format and copy the new document to a server.

See also

Concepts

PolicyItem Object

Other resources

PolicyItem Object Members


PolicyItem.Description Property (Office)

 Copy code hover
[image]

PolicyItem.Description Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a description of the current state of the policy item. Read-only.

Syntax

expression .Description

expression An expression that returns a PolicyItem object.

Return Value

String

See also

Concepts

PolicyItem Object

Other resources

PolicyItem Object Members


PolicyItem.Id Property (Office)

 Copy code hover
[image]

PolicyItem.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the ID of a policy item. PolicyItem objects are contained in ServerPolicy objects. Read-only.

Syntax

expression .Id

expression An expression that returns a PolicyItem object.

Return Value

String

See also

Concepts

PolicyItem Object

Other resources

PolicyItem Object Members


PolicyItem.Name Property (Office)

 Copy code hover
[image]

PolicyItem.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the PolicyItem object. Read-only.

Syntax

expression .Name

expression An expression that returns a PolicyItem object.

Return Value

String

See also

Concepts

PolicyItem Object

Other resources

PolicyItem Object Members


PolicyItem.Parent Property (Office)

 Copy code hover
[image]

PolicyItem.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the PolicyItem object. Read-only.

Syntax

expression .Parent

expression An expression that returns a PolicyItem object.

Return Value

Object

See also

Concepts

PolicyItem Object

Other resources

PolicyItem Object Members


ReflectionFormat Object (Office)

 Copy code hover
[image]

ReflectionFormat Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the reflection effect in Office graphics.

Example

This example sets the reflection formatting for the text for the second shape on the second slide in a PowerPoint presentation:

VBA Copy code Copy code
With ActivePresentation.Slides(1).Shapes(2)
 With .TextFrame2.TextRange.Font
 .Size = 32
 .Name = "Palatino"
 .Reflection.Type = msoReflectionType6
 End With
End With

See also

Concepts

Object Model Reference

Other resources

ReflectionFormat Object Members


ReflectionFormat Members (Office)

 Copy code hover
[image]

ReflectionFormat Members (Office)
Send feedback

Published: July 09, 2012

Represents the reflection effect in Office graphics.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ReflectionFormat object. Read-only.
Blur | Gets or sets the amount of blur, measured in points, of the shape's reflection image. Read/write
Creator | Gets a 32-bit integer that indicates the application in which the ReflectionFormat object was created. Read-only.
Offset | Gets or sets the amount of separation, measured in points, of the reflected image from the shape. Read/write
Size | Gets or sets the size, measured in percentages, of the shape's reflection image. Read/write
Transparency | Gets or sets the amount of transparency, measured in percentages, of the shape's reflection image. Read/write
Type | Gets or sets the type of the ReflectionFormat object. Read/write.


ReflectionFormat Properties (Office)

 Copy code hover
[image]

ReflectionFormat Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ReflectionFormat object. Read-only.
Blur | Gets or sets the amount of blur, measured in points, of the shape's reflection image. Read/write
Creator | Gets a 32-bit integer that indicates the application in which the ReflectionFormat object was created. Read-only.
Offset | Gets or sets the amount of separation, measured in points, of the reflected image from the shape. Read/write
Size | Gets or sets the size, measured in percentages, of the shape's reflection image. Read/write
Transparency | Gets or sets the amount of transparency, measured in percentages, of the shape's reflection image. Read/write
Type | Gets or sets the type of the ReflectionFormat object. Read/write.


ReflectionFormat.Application Property (Office)

 Copy code hover
[image]

ReflectionFormat.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ReflectionFormat object. Read-only.

Syntax

expression .Application

expression An expression that returns a ReflectionFormat object.

Return Value

Object

See also

Concepts

ReflectionFormat Object

Other resources

ReflectionFormat Object Members


ReflectionFormat.Blur Property (Office)

 Copy code hover
[image]

ReflectionFormat.Blur Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the amount of blur, measured in points, of the shape's reflection image. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Blur

expression An expression that returns a ReflectionFormat object.

See also

Concepts

ReflectionFormat Object

Other resources

ReflectionFormat Object Members


ReflectionFormat.Creator Property (Office)

 Copy code hover
[image]

ReflectionFormat.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ReflectionFormat object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a ReflectionFormat object.

Return Value

Long

See also

Concepts

ReflectionFormat Object

Other resources

ReflectionFormat Object Members


ReflectionFormat.Offset Property (Office)

 Copy code hover
[image]

ReflectionFormat.Offset Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the amount of separation, measured in points, of the reflected image from the shape. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Offset

expression An expression that returns a ReflectionFormat object.

See also

Concepts

ReflectionFormat Object

Other resources

ReflectionFormat Object Members


ReflectionFormat.Size Property (Office)

 Copy code hover
[image]

ReflectionFormat.Size Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the size, measured in percentages, of the shape's reflection image. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Size

expression An expression that returns a ReflectionFormat object.

See also

Concepts

ReflectionFormat Object

Other resources

ReflectionFormat Object Members


ReflectionFormat.Transparency Property (Office)

 Copy code hover
[image]

ReflectionFormat.Transparency Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the amount of transparency, measured in percentages, of the shape's reflection image. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Transparency

expression An expression that returns a ReflectionFormat object.

See also

Concepts

ReflectionFormat Object

Other resources

ReflectionFormat Object Members


ReflectionFormat.Type Property (Office)

 Copy code hover
[image]

ReflectionFormat.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the type of the ReflectionFormat object. Read/write.

Syntax

expression .Type

expression An expression that returns a ReflectionFormat object.

Return Value

MsoReflectionType

See also

Concepts

ReflectionFormat Object

Other resources

ReflectionFormat Object Members


Ruler2 Object (Office)

 Copy code hover
[image]

Ruler2 Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the ruler for the text in the specified shape or for all text in the specified text style. Contains tab stops and the indentation settings for text outline levels.

Remarks

Use the Ruler2 property of the TextFrame2 object to return the Ruler2 object that represents the ruler for the text in the specified shape. Use the TabStops2 property to return the TabStops2 object that contains the tab stops on the ruler. Use the Levels property to return the RulerLevels2 object that contains the indentation settings for text outline levels.

Example

The following example sets a left-aligned tab stop at 2 inches (144 Points) and sets a hanging indent for the text in object two on slide one in the active PowerPoint presentation.

VBA Copy code Copy code
With ActivePresentation.Slides(1).Shapes(2).TextFrame2.Ruler2
 .TabStops2.Add ppTabStopLeft, 144
 .Levels(1).FirstMargin = 0
 .Levels(1).LeftMargin = 36
End With

See also

Concepts

Object Model Reference

Other resources

Ruler2 Object Members


Ruler2 Members (Office)

 Copy code hover
[image]

Ruler2 Members (Office)
Send feedback

Published: July 09, 2012

Represents the ruler for the text in the specified shape or for all text in the specified text style. Contains tab stops and the indentation settings for text outline levels.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the Ruler2 object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the Ruler2 object was created. Read-only.
Levels | Gets a RulerLevels2 object that represents outline text formatting. Read-only.
Parent | Gets the Parent object for the Ruler2 object. Read-only.
TabStops | Gets a TabStops2 collection that represents the tab stops for the specified text. Read-only.


Ruler2 Properties (Office)

 Copy code hover
[image]

Ruler2 Properties (Office)
Send feedback

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the Ruler2 object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the Ruler2 object was created. Read-only.
Levels | Gets a RulerLevels2 object that represents outline text formatting. Read-only.
Parent | Gets the Parent object for the Ruler2 object. Read-only.
TabStops | Gets a TabStops2 collection that represents the tab stops for the specified text. Read-only.


Ruler2.Application Property (Office)

 Copy code hover
[image]

Ruler2.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the Ruler2 object. Read-only.

Syntax

expression .Application

expression An expression that returns a Ruler2 object.

Return Value

Object

See also

Concepts

Ruler2 Object

Other resources

Ruler2 Object Members


Ruler2.Creator Property (Office)

 Copy code hover
[image]

Ruler2.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the Ruler2 object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a Ruler2 object.

Return Value

Long

See also

Concepts

Ruler2 Object

Other resources

Ruler2 Object Members


Ruler2.Levels Property (Office)

 Copy code hover
[image]

Ruler2.Levels Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a RulerLevels2 object that represents outline text formatting. Read-only.

Syntax

expression .Levels

expression An expression that returns a Ruler2 object.

Return Value

RulerLevels2

See also

Concepts

Ruler2 Object

Other resources

Ruler2 Object Members


Ruler2.Parent Property (Office)

 Copy code hover
[image]

Ruler2.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the Ruler2 object. Read-only.

Syntax

expression .Parent

expression An expression that returns a Ruler2 object.

Return Value

Object

See also

Concepts

Ruler2 Object

Other resources

Ruler2 Object Members


Ruler2.TabStops Property (Office)

 Copy code hover
[image]

Ruler2.TabStops Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a TabStops2 collection that represents the tab stops for the specified text. Read-only.

Syntax

expression .TabStops

expression An expression that returns a Ruler2 object.

Return Value

TabStops2

See also

Concepts

Ruler2 Object

Other resources

Ruler2 Object Members


RulerLevel2 Object (Office)

 Copy code hover
[image]

RulerLevel2 Object (Office)
See also Send feedback

Published: July 09, 2012

Contains first-line indent and hanging indent information for an outline level.

Remarks

The RulerLevel2 object is a member of the RulerLevels2 collection. The RulerLevels2 collection contains a RulerLevel2 object for each of the five available outline levels.

Example

Use RulerLevels2(index), where index is the outline level, to return a single RulerLevel2 object. The following example sets the first-line indent and hanging indent for outline level one in body text on the slide master for the active presentation.

VBA Copy code Copy code
With ActivePresentation.SlideMaster _
 .TextStyles(ppBodyStyle).Ruler2.Levels(1)
 .FirstMargin = 9
 .LeftMargin = 54
End With

See also

Concepts

Object Model Reference

Other resources

RulerLevel2 Object Members


RulerLevel2 Members (Office)

 Copy code hover
[image]

RulerLevel2 Members (Office)
Send feedback

Published: July 09, 2012

Contains first-line indent and hanging indent information for an outline level.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the RulerLevel2 object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the RulerLevel2 object was created. Read-only.
FirstMargin | Gets or sets the first-line indent for the specified outline level, in points. Read/write.
LeftMargin | Gets or sets the left indent for the specified outline level, in points. Read/write.
Parent | Gets the Parent object for the RulerLevel2 object. Read-only.


RulerLevel2 Properties (Office)

 Copy code hover
[image]

RulerLevel2 Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the RulerLevel2 object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the RulerLevel2 object was created. Read-only.
FirstMargin | Gets or sets the first-line indent for the specified outline level, in points. Read/write.
LeftMargin | Gets or sets the left indent for the specified outline level, in points. Read/write.
Parent | Gets the Parent object for the RulerLevel2 object. Read-only.


RulerLevel2.Application Property (Office)

 Copy code hover
[image]

RulerLevel2.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the RulerLevel2 object. Read-only.

Syntax

expression .Application

expression An expression that returns a RulerLevel2 object.

Return Value

Object

See also

Concepts

RulerLevel2 Object

Other resources

RulerLevel2 Object Members


RulerLevel2.Creator Property (Office)

 Copy code hover
[image]

RulerLevel2.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the RulerLevel2 object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a RulerLevel2 object.

Return Value

Long

See also

Concepts

RulerLevel2 Object

Other resources

RulerLevel2 Object Members


RulerLevel2.FirstMargin Property (Office)

 Copy code hover
[image]

RulerLevel2.FirstMargin Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the first-line indent for the specified outline level, in points. Read/write.

Syntax

expression .FirstMargin

expression An expression that returns a RulerLevel2 object.

Return Value

Single

Remarks

If a paragraph begins with a bullet, the bullet position is determined by the FirstMargin property, and the position of the first text character in the paragraph is determined by the LeftMargin property.

See also

Concepts

RulerLevel2 Object

Other resources

RulerLevel2 Object Members


RulerLevel2.LeftMargin Property (Office)

 Copy code hover
[image]

RulerLevel2.LeftMargin Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the left indent for the specified outline level, in points. Read/write.

Syntax

expression .LeftMargin

expression An expression that returns a RulerLevel2 object.

Return Value

Single

Remarks

If a paragraph begins with a bullet, the bullet position is determined by the FirstMargin property, and the position of the first text character in the paragraph is determined by the LeftMargin property.

See also

Concepts

RulerLevel2 Object

Other resources

RulerLevel2 Object Members


RulerLevel2.Parent Property (Office)

 Copy code hover
[image]

RulerLevel2.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the RulerLevel2 object. Read-only.

Syntax

expression .Parent

expression An expression that returns a RulerLevel2 object.

Return Value

Object

See also

Concepts

RulerLevel2 Object

Other resources

RulerLevel2 Object Members


RulerLevels2 Object (Office)

 Copy code hover
[image]

RulerLevels2 Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of all the RulerLevel2 objects on the specified ruler.

Remarks

Each RulerLevel2 object represents the first-line and left indent for text at a particular outline level. This collection always contains five members — one for each of the available outline levels.

Example

Use the Levels property to return the RulerLevels2 collection. The following example sets the margins for the five outline levels in body text in the active presentation.

VBA Copy code Copy code
With ActivePresentation.SlideMaster.TextStyles(ppBodyStyle).Ruler2
 .Levels(1).FirstMargin = 0
 .Levels(1).LeftMargin = 40
 .Levels(2).FirstMargin = 60
 .Levels(2).LeftMargin = 100
 .Levels(3).FirstMargin = 120
 .Levels(3).LeftMargin = 160
 .Levels(4).FirstMargin = 180
 .Levels(4).LeftMargin = 220
 .Levels(5).FirstMargin = 240
 .Levels(5).LeftMargin = 280
End With

See also

Concepts

Object Model Reference

Other resources

RulerLevels2 Object Members


RulerLevels2 Members (Office)

 Copy code hover
[image]

RulerLevels2 Members (Office)
Send feedback

Published: July 09, 2012

A collection of all the RulerLevel2 objects on the specified ruler.

Methods

Name | Description
Item | Gets a member of the RulerLevels2 collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the RulerLevels2 object. Read-only.
Count | Gets a Long indicating the number of items in the RulerLevels2 collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the RulerLevels2 object was created. Read-only.
Parent | Gets the Parent object for the RulerLevels2 object. Read-only.


RulerLevels2 Properties (Office)

 Copy code hover
[image]

RulerLevels2 Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the RulerLevels2 object. Read-only.
Count | Gets a Long indicating the number of items in the RulerLevels2 collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the RulerLevels2 object was created. Read-only.
Parent | Gets the Parent object for the RulerLevels2 object. Read-only.


RulerLevels2.Application Property (Office)

 Copy code hover
[image]

RulerLevels2.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the RulerLevels2 object. Read-only.

Syntax

expression .Application

expression An expression that returns a RulerLevels2 object.

Return Value

Object

See also

Concepts

RulerLevels2 Object

Other resources

RulerLevels2 Object Members


RulerLevels2.Count Property (Office)

 Copy code hover
[image]

RulerLevels2.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the RulerLevels2 collection. Read-only.

Syntax

expression .Count

expression An expression that returns a RulerLevels2 object.

Return Value

Long

See also

Concepts

RulerLevels2 Object

Other resources

RulerLevels2 Object Members


RulerLevels2.Creator Property (Office)

 Copy code hover
[image]

RulerLevels2.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the RulerLevels2 object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a RulerLevels2 object.

Return Value

Long

See also

Concepts

RulerLevels2 Object

Other resources

RulerLevels2 Object Members


RulerLevels2.Parent Property (Office)

 Copy code hover
[image]

RulerLevels2.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the RulerLevels2 object. Read-only.

Syntax

expression .Parent

expression An expression that returns a RulerLevels2 object.

Return Value

Object

See also

Concepts

RulerLevels2 Object

Other resources

RulerLevels2 Object Members


RulerLevels2 Methods (Office)

 Copy code hover
[image]

RulerLevels2 Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Item | Gets a member of the RulerLevels2 collection.


RulerLevels2.Item Method (Office)

 Copy code hover
[image]

RulerLevels2.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Gets a member of the RulerLevels2 collection.

Syntax

expression .Item(Index)

expression An expression that returns a RulerLevels2 object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | The index number of the object to be returned.

Return Value

RulerLevel2

Example

This example sets the first-line indent and the hanging indent for outline level one in body text on the slide master for the active presentation.

VBA Copy code Copy code
With ActivePresentation.SlideMaster.TextStyles.Item(ppBodyStyle)
 With .Ruler2.Levels.Item(1) ' sets indents for level 1
 .FirstMargin = 9
 .LeftMargin = 54
 End With
End With

See also

Concepts

RulerLevels2 Object

Other resources

RulerLevels2 Object Members


ScopeFolder Object (Office)

 Copy code hover
[image]

ScopeFolder Object (Office)
See also Send feedback

Published: July 09, 2012

Corresponds to a searchable folder. ScopeFolder objects are intended for use with the SearchFolders collection.

Remarks

When you want to search specific folders you can use the methods and properties of the SearchScope object and ScopeFolders collection to retrieve ScopeFolder objects and add them to the SearchFolders collection.

In each ScopeFolder object there is a ScopeFolders collection that contains the subfolders of the parent ScopeFolder object. You can traverse the entire folder structure of a search scope (for example, all local drives) by looping through these ScopeFolders collections and returning all of the lower-level ScopeFolder objects. A ScopeFolder object with no subfolders contains an empty ScopeFolders collection.

For an example that demonstrates how to loop through all of the ScopeFolder objects in a search scope, see the SearchFolders collection topic.

You can use the Add method of the SearchFolders collection to add a ScopeFolder object to the SearchFolders collection, however, it is usually simpler to use the AddToSearchFolders method of the ScopeFolder that you want to add, as there is only one SearchFolders collection for all searches.

For an example that demonstrates how to add a ScopeFolder to the SearchFolders collection, see the SearchFolders collection topic.

Example

Use the ScopeFolder property of the SearchScope object to return the root ScopeFolder object of a search scope; for example:

Copy code Copy code
Set sf = SearchScopes.Item(1).ScopeFolder

Use the Item method of the ScopeFolders collection to return a subfolder of a root ScopeFolder object; for example:

Copy code Copy code
Set sf = SearchScopes.Item(1).ScopeFolder.ScopeFolders.Item(1)

The following example displays the root path of each directory in My Computer. To retrieve this information, the example first gets the ScopeFolder object at the root of My Computer. The path of this ScopeFolder object will always be "*". As with all ScopeFolder objects, the root object contains a ScopeFolders collection. This example loops through this ScopeFolders collection and displays the path of each ScopeFolder object in it. The paths of these ScopeFolder objects will be "A:\", "C:\", etc.

Copy code Copy code
Sub DisplayRootScopeFolders()

 'Declare variables that reference a
 'SearchScope and a ScopeFolder object.
 Dim ss As SearchScope
 Dim sf As ScopeFolder

 'Loop through the SearchScopes collection
 'and display all of the root ScopeFolders collections in
 'the My Computer scope.
 For Each ss In SearchScopes
 Select Case ss.Type
 Case msoSearchInMyComputer

 'Loop through each ScopeFolder object in
 'the ScopeFolders collection of the
 'SearchScope object and display the path.
 For Each sf In ss.ScopeFolder.ScopeFolders
 MsgBox "ScopeFolder object's path: " & sf.Path
 Next sf

 Case Else
 End Select
 Next

End Sub

See also

Concepts

Object Model Reference

Other resources

ScopeFolder Object Members


ScopeFolder Members (Office)

 Copy code hover
[image]

ScopeFolder Members (Office)
Send feedback

Published: July 09, 2012

Corresponds to a searchable folder. ScopeFolder objects are intended for use with the SearchFolders collection.

Methods

Name | Description
AddToSearchFolders | Adds a ScopeFolder object to the SearchFolders collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ScopeFolder object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ScopeFolder object was created. Read-only.
Name | Gets the name of a searchable folder. Read-only.
Path | Gets a String indicating the full path of a ScopeFolder object. Read-only.
ScopeFolders | Gets a ScopeFolders collection. The items in this collection correspond to the subfolders of the parent ScopeFolder object. Read-only.


ScopeFolder Properties (Office)

 Copy code hover
[image]

ScopeFolder Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ScopeFolder object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ScopeFolder object was created. Read-only.
Name | Gets the name of a searchable folder. Read-only.
Path | Gets a String indicating the full path of a ScopeFolder object. Read-only.
ScopeFolders | Gets a ScopeFolders collection. The items in this collection correspond to the subfolders of the parent ScopeFolder object. Read-only.


ScopeFolder.Application Property (Office)

 Copy code hover
[image]

ScopeFolder.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ScopeFolder object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a ScopeFolder object.

Return Value

Object

See also

Concepts

ScopeFolder Object

Other resources

ScopeFolder Object Members


ScopeFolder.Creator Property (Office)

 Copy code hover
[image]

ScopeFolder.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ScopeFolder object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a ScopeFolder object.

Return Value

Long

See also

Concepts

ScopeFolder Object

Other resources

ScopeFolder Object Members


ScopeFolder.Name Property (Office)

 Copy code hover
[image]

ScopeFolder.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of a searchable folder. Read-only.

Syntax

expression .Name

expression A variable that represents a ScopeFolder object.

Return Value

String

Remarks

ScopeFolder objects are intended for use with the SearchFolders collection. The SearchFolders collection defines the folders that are searched.

Example

The following example displays a message box with the name of the folder that will be searched.

Copy code Copy code
Dim sf As ScopeFolder
 Dim strScopeFolder As String

 Set sf = SearchScopes.Item(1).ScopeFolder
 strScopeFolder = sf.Name

 MsgBox ("The name of the folder that will be searched is " & strScopeFolder)

See also

Concepts

ScopeFolder Object

Other resources

ScopeFolder Object Members


ScopeFolder.Path Property (Office)

 Copy code hover
[image]

ScopeFolder.Path Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a String indicating the full path of a ScopeFolder object. Read-only.

Syntax

expression .Path

expression A variable that represents a ScopeFolder object.

Example

The following example displays the root path of each directory in My Computer. To retrieve this information, the example first gets the ScopeFolder object at the root of My Computer. The path of this ScopeFolder will always be "*". As with all ScopeFolder objects, the root object contains a ScopeFolders collection. This example loops through this ScopeFolders collection and displays the path of each ScopeFolder object in it. The paths of these ScopeFolder objects will be "A:\", "C:\", etc.

Copy code Copy code
Sub DisplayRootScopeFolders()

 'Declare variables that reference a
 'SearchScope and a ScopeFolder object.
 Dim ss As SearchScope
 Dim sf As ScopeFolder

 'Loop through the SearchScopes collection
 'and display all of the root ScopeFolders collections in
 'the My Computer scope.
 For Each ss In SearchScopes
 Select Case ss.Type
 Case msoSearchInMyComputer

 'Loop through each ScopeFolder collections in
 'the ScopeFolders collection of the
 'SearchScope object and display the path.
 For Each sf In ss.ScopeFolder.ScopeFolders
 MsgBox "Path: " & sf.Path
 Next sf

 Case Else
 End Select
 Next ss

End Sub

See also

Concepts

ScopeFolder Object

Other resources

ScopeFolder Object Members


ScopeFolder.ScopeFolders Property (Office)

 Copy code hover
[image]

ScopeFolder.ScopeFolders Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a ScopeFolders collection. The items in this collection correspond to the subfolders of the parent ScopeFolder object. Read-only.

Syntax

expression .ScopeFolders

expression A variable that represents a ScopeFolder object.

Example

The following example displays the root path of each directory in My Computer. To retrieve this information, the example first gets the ScopeFolder object at the root of My Computer. The path of this ScopeFolder will always be "*". As with all ScopeFolder objects, the root object contains a ScopeFolders collection. This example loops through this ScopeFolders collection and displays the path of each ScopeFolder object in it. The paths of these ScopeFolder objects will be "A:\", "C:\", etc.

Copy code Copy code
Sub DisplayRootScopeFolders()

 'Declare variables that reference a
 'SearchScope and a ScopeFolder object.
 Dim ss As SearchScope
 Dim sf As ScopeFolder

 'Loop through the SearchScopes collection
 'and display all of the root ScopeFolders collections in
 'the My Computer scope.
 For Each ss In SearchScopes
 Select Case ss.Type
 Case msoSearchInMyComputer

 'Loop through each ScopeFolder object in
 'the ScopeFolders collection of the
 'SearchScope object and display the path.
 For Each sf In ss.ScopeFolder.ScopeFolders
 MsgBox "Path: " & sf.Path
 Next sf

 Case Else
 End Select
 Next ss

End Sub

See also

Concepts

ScopeFolder Object

Other resources

ScopeFolder Object Members


ScopeFolder Methods (Office)

 Copy code hover
[image]

ScopeFolder Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
AddToSearchFolders | Adds a ScopeFolder object to the SearchFolders collection.


ScopeFolder.AddToSearchFolders Method (Office)

 Copy code hover
[image]

ScopeFolder.AddToSearchFolders Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a ScopeFolder object to the SearchFolders collection.

Syntax

expression .AddToSearchFolders

expression A variable that represents a ScopeFolder object.

Remarks

Although you can use the SearchFolders collection's Add method to add a ScopeFolder object to the SearchFolders collection, it is usually simpler to use the AddToSearchFolders method of the ScopeFolder object that you want to add, because there is only one SearchFolders collection for all searches.

Example

The following example adds the root ScopeFolder object to the SearchFolders collection. For a longer example that uses the AddToSearchFolders method, see the SearchFolders collection topic.

Copy code Copy code
SearchScopes(1).ScopeFolder.AddToSearchFolders

See also

Concepts

ScopeFolder Object

Other resources

ScopeFolder Object Members


ScopeFolders Object (Office)

 Copy code hover
[image]

ScopeFolders Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of ScopeFolder objects.

Remarks

Only ScopeFolder objects contain ScopeFolders collections. Each ScopeFolders collection contains the ScopeFolder objects that correspond to the subfolders of the parent ScopeFolder object.

Use the ScopeFolders property of the ScopeFolder object to return a ScopeFolders collection.

You can't add or remove ScopeFolder objects from a ScopeFolders collection.

See also

Concepts

Object Model Reference

Other resources

ScopeFolders Object Members


ScopeFolders Members (Office)

 Copy code hover
[image]

ScopeFolders Members (Office)
Send feedback

Published: July 09, 2012

A collection of ScopeFolder objects.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ScopeFolders object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the ScopeFolders collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ScopeFolders object was created. Read-only.
Item | Gets a ScopeFolder object that represents a subfolder of the parent object. Read-only.


ScopeFolders Properties (Office)

 Copy code hover
[image]

ScopeFolders Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ScopeFolders object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the ScopeFolders collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ScopeFolders object was created. Read-only.
Item | Gets a ScopeFolder object that represents a subfolder of the parent object. Read-only.


ScopeFolders.Application Property (Office)

 Copy code hover
[image]

ScopeFolders.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ScopeFolders object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a ScopeFolders object.

Return Value

Object

See also

Concepts

ScopeFolders Object

Other resources

ScopeFolders Object Members


ScopeFolders.Count Property (Office)

 Copy code hover
[image]

ScopeFolders.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the ScopeFolders collection. Read-only.

Syntax

expression .Count

expression A variable that represents a ScopeFolders object.

Return Value

Long

See also

Concepts

ScopeFolders Object

Other resources

ScopeFolders Object Members


ScopeFolders.Creator Property (Office)

 Copy code hover
[image]

ScopeFolders.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ScopeFolders object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a ScopeFolders object.

Return Value

Long

See also

Concepts

ScopeFolders Object

Other resources

ScopeFolders Object Members


ScopeFolders.Item Property (Office)

 Copy code hover
[image]

ScopeFolders.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a ScopeFolder object that represents a subfolder of the parent object. Read-only.

Syntax

expression .Item(Index)

expression Required. A variable that represents a ScopeFolders object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | Determines which subfolder to return.

See also

Concepts

ScopeFolders Object

Other resources

ScopeFolders Object Members


SearchFolders Object (Office)

 Copy code hover
[image]

SearchFolders Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of ScopeFolder objects that determines which folders are searched.

Remarks

For each application there is only a single SearchFolders collection. The contents of the collection remains after the code that calls it has finished executing. Consequently, it is important to clear the collection unless you want to include folders from previous searches in your search.

You can use the Add method of the SearchFolders collection to add a ScopeFolder object to the SearchFolders collection, however, it is usually simpler to use the AddToSearchFolders method of the ScopeFolder that you want to add, as there is only one SearchFolders collection for all searches.

See also

Concepts

Object Model Reference

Other resources

SearchFolders Object Members


SearchFolders Members (Office)

 Copy code hover
[image]

SearchFolders Members (Office)
Send feedback

Published: July 09, 2012

A collection of ScopeFolder objects that determines which folders are searched.

Methods

Name | Description
Add | Adds a search folder to a file search.
Remove | Removes the specified object from the collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SearchFolders object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SearchFolders collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SearchFolders object was created. Read-only.
Item | Gets a ScopeFolder object that represents a subfolder of the parent object. Read-only.


SearchFolders Properties (Office)

 Copy code hover
[image]

SearchFolders Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SearchFolders object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SearchFolders collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SearchFolders object was created. Read-only.
Item | Gets a ScopeFolder object that represents a subfolder of the parent object. Read-only.


SearchFolders.Application Property (Office)

 Copy code hover
[image]

SearchFolders.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SearchFolders object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a SearchFolders object.

Return Value

Object

See also

Concepts

SearchFolders Object

Other resources

SearchFolders Object Members


SearchFolders.Count Property (Office)

 Copy code hover
[image]

SearchFolders.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the SearchFolders collection. Read-only.

Syntax

expression .Count

expression A variable that represents a SearchFolders object.

Return Value

Long

See also

Concepts

SearchFolders Object

Other resources

SearchFolders Object Members


SearchFolders.Creator Property (Office)

 Copy code hover
[image]

SearchFolders.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SearchFolders object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a SearchFolders object.

Return Value

Long

See also

Concepts

SearchFolders Object

Other resources

SearchFolders Object Members


SearchFolders.Item Property (Office)

 Copy code hover
[image]

SearchFolders.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a ScopeFolder object that represents a subfolder of the parent object. Read-only.

Syntax

expression .Item(Index)

expression Required. A variable that represents a SearchFolders object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | Determines which subfolder to return.

See also

Concepts

SearchFolders Object

Other resources

SearchFolders Object Members


SearchFolders Methods (Office)

 Copy code hover
[image]

SearchFolders Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a search folder to a file search.
Remove | Removes the specified object from the collection.


SearchFolders.Add Method (Office)

 Copy code hover
[image]

SearchFolders.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a search folder to a file search.

Syntax

expression .Add(ScopeFolder)

expression Required. A variable that represents a SearchFolders object.

Parameters

Name | Required/Optional | Data Type | Description
ScopeFolder | Required | object | The folder to add to the search.

See also

Concepts

SearchFolders Object

Other resources

SearchFolders Object Members


SearchFolders.Remove Method (Office)

 Copy code hover
[image]

SearchFolders.Remove Method (Office)
See also Send feedback

Published: July 09, 2012

Removes the specified object from the collection.

Syntax

expression .Remove(Index)

expression Required. A variable that represents a SearchFolders object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | The index number of the folder to be removed.

See also

Concepts

SearchFolders Object

Other resources

SearchFolders Object Members


SearchScope Object (Office)

 Copy code hover
[image]

SearchScope Object (Office)
See also Send feedback

Published: July 09, 2012

Corresponds to a type of folder tree that can be searched.

Remarks

Each SearchScope object contains a single ScopeFolder object that corresponds to the root folder of the search scope.

Use the Item method of the SearchScopes collection to return a SearchScope object; for example:

Copy code Copy code
Dim ss As SearchScope
Set ss = SearchScopes.Item(1)

Ultimately, the SearchScope object is intended to provide access to ScopeFolder objects that can be added to the SearchFolders collection. For an example that demonstrates how this is accomplished, see the SearchFolders collection topic.

See the ScopeFolder object topic to see a simple example of how to return a ScopeFolder object from a SearchScope object.

Example

The following example displays all of the currently available SearchScope objects.

Copy code Copy code
Sub DisplayAvailableScopes()

 'Declare a variable that references a
 'SearchScope object.
 Dim ss As SearchScope

 'Loop through the SearchScopes collection.
 For Each ss In SearchScopes
 Select Case ss.Type
 Case msoSearchInMyComputer
 MsgBox "My Computer is an available search scope."
 Case msoSearchInMyNetworkPlaces
 MsgBox "My Network Places is an available search scope."
 Case msoSearchInOutlook
 MsgBox "Outlook is an available search scope."
 Case msoSearchInCustom
 MsgBox "A custom search scope is available."
 Case Else
 MsgBox "Can't determine search scope."
 End Select
 Next ss

End Sub

See also

Concepts

Object Model Reference

Other resources

SearchScope Object Members


SearchScope Members (Office)

 Copy code hover
[image]

SearchScope Members (Office)
Send feedback

Published: July 09, 2012

Corresponds to a type of folder tree that can be searched.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SearchScope object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SearchScope object was created. Read-only.
ScopeFolder | Gets a ScopeFolder object. Read-only.
Type | Gets a value that corresponds to the type of SearchScope object. The type indicates the area in which to search for files. Read-only.


SearchScope Properties (Office)

 Copy code hover
[image]

SearchScope Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SearchScope object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SearchScope object was created. Read-only.
ScopeFolder | Gets a ScopeFolder object. Read-only.
Type | Gets a value that corresponds to the type of SearchScope object. The type indicates the area in which to search for files. Read-only.


SearchScope.Application Property (Office)

 Copy code hover
[image]

SearchScope.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SearchScope object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a SearchScope object.

Return Value

Object

See also

Concepts

SearchScope Object

Other resources

SearchScope Object Members


SearchScope.Creator Property (Office)

 Copy code hover
[image]

SearchScope.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SearchScope object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a SearchScope object.

Return Value

Long

See also

Concepts

SearchScope Object

Other resources

SearchScope Object Members


SearchScope.ScopeFolder Property (Office)

 Copy code hover
[image]

SearchScope.ScopeFolder Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a ScopeFolder object. Read-only.

Syntax

expression .ScopeFolder

expression A variable that represents a SearchScope object.

Example

The following example displays the root path of each directory in My Computer. To retrieve this information, the example first gets the ScopeFolder object at the root of My Computer. The path of this ScopeFolder will always be "*". As with all ScopeFolder objects, the root object contains a ScopeFolders collection. This example loops through this ScopeFolders collection and displays the path of each ScopeFolder object in it. The paths of these ScopeFolder objects will be "A:\", "C:\", etc.

Copy code Copy code
Sub DisplayRootScopeFolders()

 'Declare variables that reference a
 'SearchScope and a ScopeFolder object.
 Dim ss As SearchScope
 Dim sf As ScopeFolder

 'Loop through the SearchScopes collection
 'and display all of the root ScopeFolders collections in
 'the My Computer scope.
 For Each ss In SearchScopes
 Select Case ss.Type
 Case msoSearchInMyComputer

 'Loop through each ScopeFolder object in
 'the ScopeFolders collection of the
 'SearchScope object and display the path.
 For Each sf In ss.ScopeFolder.ScopeFolders
 MsgBox "Path: " & sf.Path
 Next sf

 Case Else
 End Select
 Next ss

End Sub

See also

Concepts

SearchScope Object

Other resources

SearchScope Object Members


SearchScope.Type Property (Office)

 Copy code hover
[image]

SearchScope.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value that corresponds to the type of SearchScope object. The type indicates the area in which to search for files. Read-only.

Syntax

expression .Type

expression Required. A variable that represents a SearchScope object.

See also

Concepts

SearchScope Object

Other resources

SearchScope Object Members


SearchScopes Object (Office)

 Copy code hover
[image]

SearchScopes Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of SearchScope objects.

Remarks

You can't add or remove SearchScope objects from the SearchScopes collection.

See also

Concepts

Object Model Reference

Other resources

SearchScopes Object Members


SearchScopes Members (Office)

 Copy code hover
[image]

SearchScopes Members (Office)
Send feedback

Published: July 09, 2012

A collection of SearchScope objects.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SearchScopes object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SearchScopes object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SearchScopes object was created. Read-only.
Item | Gets a SearchScope object that corresponds to an area in which to perform a file search, such as local drives or Microsoft Outlook folders. Read-only.


SearchScopes Properties (Office)

 Copy code hover
[image]

SearchScopes Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SearchScopes object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SearchScopes object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SearchScopes object was created. Read-only.
Item | Gets a SearchScope object that corresponds to an area in which to perform a file search, such as local drives or Microsoft Outlook folders. Read-only.


SearchScopes.Application Property (Office)

 Copy code hover
[image]

SearchScopes.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SearchScopes object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a SearchScopes object.

Return Value

Object

See also

Concepts

SearchScopes Object

Other resources

SearchScopes Object Members


SearchScopes.Count Property (Office)

 Copy code hover
[image]

SearchScopes.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the SearchScopes object. Read-only.

Syntax

expression .Count

expression A variable that represents a SearchScopes object.

Return Value

Long

See also

Concepts

SearchScopes Object

Other resources

SearchScopes Object Members


SearchScopes.Creator Property (Office)

 Copy code hover
[image]

SearchScopes.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SearchScopes object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a SearchScopes object.

Return Value

Long

See also

Concepts

SearchScopes Object

Other resources

SearchScopes Object Members


SearchScopes.Item Property (Office)

 Copy code hover
[image]

SearchScopes.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a SearchScope object that corresponds to an area in which to perform a file search, such as local drives or Microsoft Outlook folders. Read-only.

Syntax

expression .Item(Index)

expression Required. A variable that represents a SearchScopes object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | Determines which SearchScope object to return.

See also

Concepts

SearchScopes Object

Other resources

SearchScopes Object Members


ServerPolicy Object (Office)

 Copy code hover
[image]

ServerPolicy Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a policy specified for a document type stored on a server running Microsoft Office SharePoint Server.

Remarks

The ServerPolicy object is composed of individual PolicyItem objects representing the individual policy definitions for the active document.

Example

The following example lists the name and description of all of the policy items for the active document.

VBA Copy code Copy code
Sub ListPolicyItems()
Dim objSrvPolicy As ServerPolicy
Dim objPolicyItem As PolicyItem
Dim strPolicyItemList As String

Set objSrvPolicy = ActiveDocument.ServerPolicy

For Each objPolicyItem In objSrvPolicy
 strPolicyItemList = "Policy Item " & objPolicyItem.Name & " - " & _
 objPolicyItem.Description & vbCrLf
Next
MsgBox (strPolicyItemList)

End Sub

See also

Concepts

Object Model Reference

Other resources

ServerPolicy Object Members


ServerPolicy Members (Office)

 Copy code hover
[image]

ServerPolicy Members (Office)
Send feedback

Published: July 09, 2012

Represents a policy specified for a document type stored on a server running Microsoft Office SharePoint Server.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ServerPolicy object. Read-only.
BlockPreview | Gets a Boolean value that indicates whether you can preview items using this policy. Read-only.
Count | Gets a Long indicating the number of items in the ServerPolicy collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ServerPolicy object was created. Read-only.
Description | A description of what the server policy is and its purpose. Read-only.
Id | Gets the ID of a server policy. Read-only.
Item | Gets a PolicyItem object from the ServerPolicy collection. Read-only.
Name | Gets the name of the ServerPolicy object. Read-only.
Parent | Gets the Parent object for the ServerPolicy object. Read-only.
Statement | Gets the information specified in the Policy Statement. Read-only.


ServerPolicy Properties (Office)

 Copy code hover
[image]

ServerPolicy Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ServerPolicy object. Read-only.
BlockPreview | Gets a Boolean value that indicates whether you can preview items using this policy. Read-only.
Count | Gets a Long indicating the number of items in the ServerPolicy collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ServerPolicy object was created. Read-only.
Description | A description of what the server policy is and its purpose. Read-only.
Id | Gets the ID of a server policy. Read-only.
Item | Gets a PolicyItem object from the ServerPolicy collection. Read-only.
Name | Gets the name of the ServerPolicy object. Read-only.
Parent | Gets the Parent object for the ServerPolicy object. Read-only.
Statement | Gets the information specified in the Policy Statement. Read-only.


ServerPolicy.Application Property (Office)

 Copy code hover
[image]

ServerPolicy.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ServerPolicy object. Read-only.

Syntax

expression .Application

expression An expression that returns a ServerPolicy object.

Return Value

Object

See also

Concepts

ServerPolicy Object

Other resources

ServerPolicy Object Members


ServerPolicy.BlockPreview Property (Office)

 Copy code hover
[image]

ServerPolicy.BlockPreview Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value that indicates whether you can preview items using this policy. Read-only.

Syntax

expression .BlockPreview

expression An expression that returns a ServerPolicy object.

Return Value

Boolean

See also

Concepts

ServerPolicy Object

Other resources

ServerPolicy Object Members


ServerPolicy.Count Property (Office)

 Copy code hover
[image]

ServerPolicy.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the ServerPolicy collection. Read-only.

Syntax

expression .Count

expression An expression that returns a ServerPolicy object.

Return Value

Long

See also

Concepts

ServerPolicy Object

Other resources

ServerPolicy Object Members


ServerPolicy.Creator Property (Office)

 Copy code hover
[image]

ServerPolicy.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ServerPolicy object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a ServerPolicy object.

Return Value

Long

See also

Concepts

ServerPolicy Object

Other resources

ServerPolicy Object Members


ServerPolicy.Description Property (Office)

 Copy code hover
[image]

ServerPolicy.Description Property (Office)
See also Send feedback

Published: July 09, 2012

A description of what the server policy is and its purpose. Read-only.

Syntax

expression .Description

expression An expression that returns a ServerPolicy object.

Return Value

String

See also

Concepts

ServerPolicy Object

Other resources

ServerPolicy Object Members


ServerPolicy.Id Property (Office)

 Copy code hover
[image]

ServerPolicy.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the ID of a server policy. Read-only.

Syntax

expression .Id

expression An expression that returns a ServerPolicy object.

Return Value

String

See also

Concepts

ServerPolicy Object

Other resources

ServerPolicy Object Members


ServerPolicy.Item Property (Office)

 Copy code hover
[image]

ServerPolicy.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a PolicyItem object from the ServerPolicy collection. Read-only.

Syntax

expression .Item(Index)

expression An expression that returns a ServerPolicy object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | The name or index number of the PolicyItem object to be returned.

Return Value

PolicyItem

See also

Concepts

ServerPolicy Object

Other resources

ServerPolicy Object Members


ServerPolicy.Name Property (Office)

 Copy code hover
[image]

ServerPolicy.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the ServerPolicy object. Read-only.

Syntax

expression .Name

expression An expression that returns a ServerPolicy object.

Return Value

String

See also

Concepts

ServerPolicy Object

Other resources

ServerPolicy Object Members


ServerPolicy.Parent Property (Office)

 Copy code hover
[image]

ServerPolicy.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ServerPolicy object. Read-only.

Syntax

expression .Parent

expression An expression that returns a ServerPolicy object.

Return Value

Object

See also

Concepts

ServerPolicy Object

Other resources

ServerPolicy Object Members


ServerPolicy.Statement Property (Office)

 Copy code hover
[image]

ServerPolicy.Statement Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the information specified in the Policy Statement. Read-only.

Syntax

expression .Statement

expression An expression that returns a ServerPolicy object.

Return Value

String

Remarks

The contents of the Policy Statement is displayed as a "business bar" notification in the Office client application when a document that contains the policy is displayed.

See also

Concepts

ServerPolicy Object

Other resources

ServerPolicy Object Members


SharedWorkspace Object (Office)

 Copy code hover
[image]

SharedWorkspace Object (Office)
See also Send feedback

Published: July 09, 2012

The SharedWorkspace property of a Document object in Microsoft Word, a Workbook object in Microsoft Excel, and a Presentation object in Microsoft PowerPoint returns a SharedWorkspace object which allows the developer to add the active document to a SharePoint site and to manage other objects in the shared workspace site.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Remarks

Use the SharedWorkspace object to add the active Word, Excel or PowerPoint document to a SharePoint document workspace site on the server to take advantage of the workspace's collaboration features, or to disconnect or remove the document from the workspace site. Use the SharedWorkspace object's collections to manage files, folders, links, members and tasks associated with the shared document.

The SharedWorkspace object model is available whether or not a document is stored in a workspace. The SharedWorkspace property of the Document, Workbook, and Presentation objects does not return Nothing when the document is not shared. Use the Connected property of the SharedWorkspace object to determine whether the active document is in fact saved in and connected to a shared workspace.

Users require appropriate permissions to use the objects, properties and methods in the SharedWorkspace object hierarchy.

Use the SharedWorkspaceFiles collection, accessed through the Files property of the SharedWorkspace object, to manage documents and files saved in a shared workspace.

Use the SharedWorkspaceFolders collection, accessed through the Folders property of the SharedWorkspace object, to manage subfolders within the main document library folder of a shared workspace.

Use the SharedWorkspaceLinks collection, accessed through the Links property of the SharedWorkspace object, to manage links to additional documents and information of interest to the members who are collaborating on the documents in the shared workspace.

Use the SharedWorkspaceMembers collection, accessed through the Members property of the SharedWorkspace object, to manage users who have rights to participate in a shared workspace and to collaborate on the shared documents saved in the workspace.

Use the SharedWorkspaceTasks collection, accessed through the Tasks property of the SharedWorkspace object, to manage tasks assigned to the members who are collaborating on the documents in the shared workspace.

Use the CreateNew method to create a new document workspace and to add the active document to the workspace. Use the Name and URL properties to return information about the workspace.

The SharedWorkspace object uses a local cache of objects and properties from the server. The developer may need to update this cache before performing certain operations, or to save cached property changes back to the server. Use the Refresh method of the SharedWorkspace object to refresh the local cache from the server, and the LastRefreshed property to determine when the refresh operation last took place. Use the Save method of the SharedWorkspaceLink and SharedWorkspaceTask objects after modifying their properties locally, to upload the changes to the server.

Use the Disconnect method to disconnect the local copy of the active document from the shared workspace, while leaving the shared copy intact in the workspace. Use the RemoveDocument method to remove the shared document from the shared workspace entirely.

Users require appropriate permissions to use the objects, properties and methods in the SharedWorkspace object hierarchy. Use the Role argument when adding members to the SharedWorkspaceMembers collection to specify the set of permissions specific to each workspace member.

When using the SharedWorkspace object model, it is possible to create conditions where the SharedWorkspace object cache is not synchronized with the user interface displayed in the Shared Workspace pane of the active document. For example, if the CreateNew method programmatically adds the active document to a new workspace while the Shared Workspace pane is open, the Shared Workspace pane will continue to display the Create button. In circumstances like these, if the user makes a selection in the Shared Workspace pane that is no longer valid, an error is raised and a refresh operation is carried out to synchronize the display with the current document state and shared workspace data.

The Document, Workbook, and Presentation objects also have a Sync property which returns a Sync object. Use the Sync object and its properties and methods to manage the synchronization of the local and the server copies of the shared document.

Example

The following example displays the properties of the shared workspace to which the active document is connected.

Copy code Copy code
    Dim swsWorkspace As Office.SharedWorkspace
    Dim strSWSInfo As String
    Set swsWorkspace = ActiveWorkbook.SharedWorkspace
    strSWSInfo = swsWorkspace.Name & vbCrLf & _
        " - URL: " & swsWorkspace.URL & vbCrLf & _
        "The shared workspace contains " & vbCrLf & _
        " - Files: " & swsWorkspace.Files.Count & vbCrLf & _
        " - Folders: " & swsWorkspace.Folders.Count & vbCrLf & _
        " - Links: " & swsWorkspace.Links.Count & vbCrLf & _
        " - Members: " & swsWorkspace.Members.Count & vbCrLf & _
        " - Tasks: " & swsWorkspace.Tasks.Count & vbCrLf
    MsgBox strSWSInfo, vbInformation + vbOKOnly, _
        "Shared Workspace Information"
    Set swsWorkspace = Nothing

See also

Concepts

Object Model Reference

Other resources

SharedWorkspace Object Members


SharedWorkspace Members (Office)

 Copy code hover
[image]

SharedWorkspace Members (Office)
Send feedback

Published: July 09, 2012

The SharedWorkspace property of a Document object in Microsoft Word, a Workbook object in Microsoft Excel, and a Presentation object in Microsoft PowerPoint returns a SharedWorkspace object which allows the developer to add the active document to a SharePoint site and to manage other objects in the shared workspace site.

Methods

Name | Description
CreateNew | Creates a document workspace site on the server and adds the active document to the new shared workspace site.
Delete | Deletes the current shared workspace and all data within it.
Disconnect | Disconnects the local copy of the active document from the shared workspace site.
Refresh | Refreshes the local cache of the SharedWorkspace object's files, folders, links, members, and tasks from the server.
RemoveDocument | Removes the active document from the shared workspace site.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspace object (you can use this property with an Automation object to return that object's container application). Read-only.
Connected | Gets a Boolean value that indicates whether or not the active document is currently saved in and connected to a shared workspace. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspace object was created. Read-only.
Files | Provides access to the SharedWorkspaceFile objects in the SharedWorkspace. Read-only.
Folders | Gets a SharedWorkspaceFolders collection that represents the list of subfolders in the document library associated with the current shared workspace. Read-only.
LastRefreshed | Gets the date and time when the Refresh method was most recently called. Read-only.
Links | Gets a SharedWorkspaceLinks collection that represents the list of links saved in the current shared workspace. Read-only.
Members | Gets a SharedWorkspaceMembers collection that represents the list of members in the current shared workspace. Read-only.
Name | Gets or sets the display name of the shared workspace site. Read/write.
Parent | Gets the Parent object for the SharedWorkspace object. Read-only.
SourceURL | Designates the location of the public copy of a shared document to which changes should be published back after the document has been revised in a separate document workspace site. Read-only.
Tasks | Gets a SharedWorkspaceTasks collection that represents the list of tasks in the current shared workspace. Read-only.
URL | Gets the top-level Uniform Resource Locator (URL) of the shared workspace. Read-only.


SharedWorkspace Properties (Office)

 Copy code hover
[image]

SharedWorkspace Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspace object (you can use this property with an Automation object to return that object's container application). Read-only.
Connected | Gets a Boolean value that indicates whether or not the active document is currently saved in and connected to a shared workspace. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspace object was created. Read-only.
Files | Provides access to the SharedWorkspaceFile objects in the SharedWorkspace. Read-only.
Folders | Gets a SharedWorkspaceFolders collection that represents the list of subfolders in the document library associated with the current shared workspace. Read-only.
LastRefreshed | Gets the date and time when the Refresh method was most recently called. Read-only.
Links | Gets a SharedWorkspaceLinks collection that represents the list of links saved in the current shared workspace. Read-only.
Members | Gets a SharedWorkspaceMembers collection that represents the list of members in the current shared workspace. Read-only.
Name | Gets or sets the display name of the shared workspace site. Read/write.
Parent | Gets the Parent object for the SharedWorkspace object. Read-only.
SourceURL | Designates the location of the public copy of a shared document to which changes should be published back after the document has been revised in a separate document workspace site. Read-only.
Tasks | Gets a SharedWorkspaceTasks collection that represents the list of tasks in the current shared workspace. Read-only.
URL | Gets the top-level Uniform Resource Locator (URL) of the shared workspace. Read-only.


SharedWorkspace.Application Property (Office)

 Copy code hover
[image]

SharedWorkspace.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SharedWorkspace object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a SharedWorkspace object.

Return Value

Object

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Connected Property (Office)

 Copy code hover
[image]

SharedWorkspace.Connected Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value that indicates whether or not the active document is currently saved in and connected to a shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Connected

expression A variable that represents a SharedWorkspace object.

Remarks

Use the Disconnect method of the SharedWorkspace object to disconnect the local copy of the active document from the shared workspace. Use the RemoveDocument method to remove the document from the shared workspace.

Example

The following example checks the Connected property to determine whether the active document is already saved in a shared workspace.

VBA Copy code Copy code
    If ActiveWorkbook.SharedWorkspace.Connected Then
        MsgBox "This document is already saved in a shared workspace."
    End If

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Creator Property (Office)

 Copy code hover
[image]

SharedWorkspace.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SharedWorkspace object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a SharedWorkspace object.

Return Value

Long

Remarks

As an example, if the object was created in Microsoft Word, this property returns 1297307460, which represents the string "MSWD"; in Microsoft Excel, this property returns 1480803660. This value can also be represented by the constant wdCreatorCode in Word, or xlCreatorCode in Excel. The Creator property was primarily designed to be used on the Macintosh, where each application has a four-character creator code. For example, Microsoft Word has the creator code MSWD. For additional information about this property, consult the language reference Help included with Microsoft Office Macintosh Edition.

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Files Property (Office)

 Copy code hover
[image]

SharedWorkspace.Files Property (Office)
See also Send feedback

Published: July 09, 2012

Provides access to the SharedWorkspaceFile objects in the SharedWorkspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Files

expression A variable that represents a SharedWorkspace object.

Example

The following example lists the files saved in the current shared workspace.

VBA Copy code Copy code
    Dim swsFiles As Office.SharedWorkspaceFiles
    Set swsFiles = ActiveWorkbook.SharedWorkspace.Files
    MsgBox "There are " & swsFiles.Count & _
        " file(s)
        vbInformation + vbOKOnly, _
        "Collection Information"
    Set swsFiles = Nothing

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Folders Property (Office)

 Copy code hover
[image]

SharedWorkspace.Folders Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a SharedWorkspaceFolders collection that represents the list of subfolders in the document library associated with the current shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Folders

expression A variable that represents a SharedWorkspace object.

Remarks

The SharedWorkspaceFolders collection does not include the root document library folder itself, which by default is named "Shared Documents".

Example

The following example lists the subfolders in the current shared workspace.

VBA Copy code Copy code
    Dim swsFolders As Office.SharedWorkspaceFolders
    Set swsFolders = ActiveWorkbook.SharedWorkspace.Folders
    MsgBox "There are " & swsFolders.Count & _
        " folder(s) in the current shared workspace.", _
        vbInformation + vbOKOnly, _
        "Collection Information"
    Set swsFolders = Nothing

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.LastRefreshed Property (Office)

 Copy code hover
[image]

SharedWorkspace.LastRefreshed Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the date and time when the Refresh method was most recently called. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .LastRefreshed

expression A variable that represents a SharedWorkspace object.

Remarks

The LastRefreshed property raises an error if the Refresh method has never been called.

Example

The following example refreshes the shared workspace if it has not been refreshed in the last 3 minutes. The example also handles the error condition where the workspace has not yet been refreshed.

VBA Copy code Copy code
    On Error GoTo err_NeverRefreshed
    If DateDiff("s", ActiveWorkbook.SharedWorkspace.LastRefreshed, Now) > 180 Then
        ActiveWorkbook.SharedWorkspace.Refresh
    End If
    Exit Sub

err_NeverRefreshed:
          ActiveWorkbook.SharedWorkspace.Refresh

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Links Property (Office)

 Copy code hover
[image]

SharedWorkspace.Links Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a SharedWorkspaceLinks collection that represents the list of links saved in the current shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Links

expression A variable that represents a SharedWorkspace object.

Example

The following example lists the links saved in the current shared workspace.

VBA Copy code Copy code
  Dim swsLinks As Office.SharedWorkspaceLinks
    Set swsLinks = ActiveWorkbook.SharedWorkspace.Links
    MsgBox "There are " & swsLinks.Count & _
        " link(s) in the current shared workspace.", _
        vbInformation + vbOKOnly, _
        "Collection Information"
    Set swsLinks = Nothing

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Members Property (Office)

 Copy code hover
[image]

SharedWorkspace.Members Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a SharedWorkspaceMembers collection that represents the list of members in the current shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Members

expression A variable that represents a SharedWorkspace object.

Example

The following example lists the members in the current shared workspace.

VBA Copy code Copy code
Dim swsMembers As Office.SharedWorkspaceMembers
    Set swsMembers = ActiveWorkbook.SharedWorkspace.Members
    MsgBox "There are " & swsMembers.Count & _
        " member(s) in the current shared workspace.", _
        vbInformation + vbOKOnly, _
        "Collection Information"
    Set swsMembers = Nothing

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Name Property (Office)

 Copy code hover
[image]

SharedWorkspace.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the display name of the shared workspace site. Read/write.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Name

expression A variable that represents a SharedWorkspace object.

Return Value

String

Example

The following example displays the properties of the shared workspace to which the active document is connected.

VBA Copy code Copy code
Dim swsWorkspace As Office.SharedWorkspace
    Dim strSWSInfo As String
    Set swsWorkspace = ActiveWorkbook.SharedWorkspace
    strSWSInfo = swsWorkspace.Name & vbCrLf & _
        " - URL: " & swsWorkspace.URL & vbCrLf & _
        "The shared workspace contains " & vbCrLf & _
        " - Files: " & swsWorkspace.Files.Count & vbCrLf & _
        " - Folders: " & swsWorkspace.Folders.Count & vbCrLf & _
        " - Links: " & swsWorkspace.Links.Count & vbCrLf & _
        " - Members: " & swsWorkspace.Members.Count & vbCrLf & _
        " - Tasks: " & swsWorkspace.Tasks.Count & vbCrLf
    MsgBox strSWSInfo, vbInformation + vbOKOnly, _
        "Shared Workspace Information"
    Set swsWorkspace = Nothing

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Parent Property (Office)

 Copy code hover
[image]

SharedWorkspace.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the SharedWorkspace object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a SharedWorkspace object.

Return Value

Object

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.SourceURL Property (Office)

 Copy code hover
[image]

SharedWorkspace.SourceURL Property (Office)
See also Send feedback

Published: July 09, 2012

Designates the location of the public copy of a shared document to which changes should be published back after the document has been revised in a separate document workspace site. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .SourceURL

expression A variable that represents a SharedWorkspace object.

Remarks

The Microsoft SharePoint Team Services user interface allows users to copy a public shared document from a document library to a separate document workspace for temporary collaboration purposes, then publish changes back to the original source location. The SourceURL property indicates the original source location of a document copy stored in a temporary workspace.

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Tasks Property (Office)

 Copy code hover
[image]

SharedWorkspace.Tasks Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a SharedWorkspaceTasks collection that represents the list of tasks in the current shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Tasks

expression A variable that represents a SharedWorkspace object.

Example

The following example lists the tasks in the current shared workspace.

Copy code Copy code
   Dim swsTasks As Office.SharedWorkspaceTasks
    Set swsTasks = ActiveWorkbook.SharedWorkspace.Tasks
    MsgBox "There are " & swsTasks.Count & _
        " task(s) in the current shared workspace.", _
        vbInformation + vbOKOnly, _
        "Collection Information"
    Set swsTasks = Nothing

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.URL Property (Office)

 Copy code hover
[image]

SharedWorkspace.URL Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the top-level Uniform Resource Locator (URL) of the shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .URL

expression A variable that represents a SharedWorkspace object.

Return Value

String

Remarks

The URL property returns the address of the shared workspace in this format: http://server/sites/user/workspace/. The URL property returns a URL-encoded string. For example, a space in the folder name is represented by %20. Use a simple function like the following example to replace this escaped character with a space. Private Function URLDecode(URLtoDecode As String) As String URLDecode = Replace(URLtoDecode, "%20", " ") End Function

Example

The following example displays the base URL of the shared workspace.

Copy code Copy code
 MsgBox "URL: " & ActiveWorkbook.SharedWorkspaceLink.URL, _
        vbInformation + vbOKOnly, "Shared Workspace URL"

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace Methods (Office)

 Copy code hover
[image]

SharedWorkspace Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
CreateNew | Creates a document workspace site on the server and adds the active document to the new shared workspace site.
Delete | Deletes the current shared workspace and all data within it.
Disconnect | Disconnects the local copy of the active document from the shared workspace site.
Refresh | Refreshes the local cache of the SharedWorkspace object's files, folders, links, members, and tasks from the server.
RemoveDocument | Removes the active document from the shared workspace site.


SharedWorkspace.CreateNew Method (Office)

 Copy code hover
[image]

SharedWorkspace.CreateNew Method (Office)
See also Send feedback

Published: July 09, 2012

Creates a document workspace site on the server and adds the active document to the new shared workspace site.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .CreateNew(URL, Name)

expression A variable that represents a SharedWorkspace object.

Parameters

Name | Required/Optional | Data Type | Description
URL | Optional | Variant | The URL for the parent folder in which the new shared workspace is to be created. If you do not supply a URL, the site is created in the user's default server location.
Name | Optional | Variant | The name of the new shared workspace site. The default value is the name of the active document without its file name extension. For example, if you create a workspace site for "Budget.xls", the name of the new site becomes "Budget".

Remarks

Use the CreateNew method to create a shared workspace site for the active document. Omit the 2 optional arguments to create the site using the name of the active document in the user's default server location.

The CreateNew method raises an error if the active document has changes that have not been saved. The document must be saved before you can add it to a shared workspace site.

Note Note

Immediately after creating a shared workspace site and then creating the active document in the site, the active document is closed and then reopened so that the copy of the active document that the user sees is the one located in the site. If the active document was saved prior to invoking the CreateNew method, that copy of the document is unavailable for the period of time while the new copy is created. This causes an exception for any code that tries to access the saved copy during the creation time period. One workaround is to impose a short delay (suggested 15 seconds or more) before attempting to access the active document from any script. In addition, any cached object that points to the local document msut be updated to point to the document in the shared workspace site.

Example

The following example creates a shared workspace site at the URL http://server/sites/mysite/, names the workspace "My Shared Budget Document", and adds the active document to the site. The URL property of the new shared workspace site returns http://server/sites/mysite/My%20Shared%20Budget%20Document/, the Name property returns "My Shared Budget Document, and Count property of the SharedWorkspaceFiles collection shows a single file.

VBA Copy code Copy code
   Dim sws As Office.SharedWorkspace
    Dim strSWSInfo As String
    Set sws = ActiveWorkbook.SharedWorkspace
    sws.CreateNew "http://server/sites/mysite/", "My Shared Budget Document"
    strSWSInfo = "Name: " & sws.Name & vbCrLf & _
        "URL: " & sws.URL & vbCrLf & _
        "File(s): " & sws.Files.Count
    MsgBox strSWSInfo, vbInformation + vbOKOnly, _
        "New Shared Workspace Information"
    Set sws = Nothing

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Delete Method (Office)

 Copy code hover
[image]

SharedWorkspace.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the current shared workspace and all data within it.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Delete

expression Required. A variable that represents a SharedWorkspace object.

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Disconnect Method (Office)

 Copy code hover
[image]

SharedWorkspace.Disconnect Method (Office)
See also Send feedback

Published: July 09, 2012

Disconnects the local copy of the active document from the shared workspace site.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Disconnect

expression A variable that represents a SharedWorkspace object.

Remarks

Use the Disconnect method to detach the local copy of the active document from the shared workspace site. This method leaves the shared document on the server; however, the local copy will no longer be synchronized with the shared copy and will no longer benefit from the other collaboration features of the shared workspace. Use the RemoveDocument method to remove the shared document from the server.

Example

The following example determines whether the active document is connected to a shared workspace site, then offers the user the option of disconnecting it.

VBA Copy code Copy code
   Dim r As Long
    If ActiveWorkbook.SharedWorkspace.Connected Then
        r = MsgBox("Are you sure you want to disconnect this document?", _
            vbQuestion + vbOKCancel, "Are you sure?")
        If r = vbOK Then
            ActiveWorkbook.SharedWorkspace.Disconnect
            MsgBox "The document has been disconnected.", _
                vbInformation + vbOKOnly, "Disconnected"
        Else
            MsgBox "Disconnect canceled.", _
                vbInformation + vbOKOnly, "Still Connected"
        End If
    Else
        MsgBox "The active document is not connected to a shared workspace.", _
            vbInformation + vbOKOnly, "Not Connected"
    End If

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.Refresh Method (Office)

 Copy code hover
[image]

SharedWorkspace.Refresh Method (Office)
See also Send feedback

Published: July 09, 2012

Refreshes the local cache of the SharedWorkspace object's files, folders, links, members, and tasks from the server.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Refresh

expression A variable that represents a SharedWorkspace object.

Remarks

Use the Refresh method to ensure that you are working with the most up-to-date list of objects and their properties from the shared workspace.

Example

The following example refreshes the shared workspace if it has not been refreshed in the last 3 minutes. The example also handles the error condition where the workspace has not yet been refreshed.

VBA Copy code Copy code
    On Error GoTo err_NeverRefreshed
    If DateDiff("s", ActiveWorkbook.SharedWorkspace.LastRefreshed, Now) > 180 Then
        ActiveWorkbook.SharedWorkspace.Refresh
    End If
    Exit Sub

err_NeverRefreshed:
          ActiveWorkbook.SharedWorkspace.Refresh

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspace.RemoveDocument Method (Office)

 Copy code hover
[image]

SharedWorkspace.RemoveDocument Method (Office)
See also Send feedback

Published: July 09, 2012

Removes the active document from the shared workspace site.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .RemoveDocument

expression A variable that represents a SharedWorkspace object.

Remarks

If the user does not have permission to remove the shared workspace document from the server, then the server copy remains intact, but the local copy of the document is disconnected from the shared workspace. In the case where the document was opened directly from the workspace, then removed from the workspace using RemoveDocument, the document must be saved to another location before closing; otherwise, it remains in the workspace.

Use the Disconnect method to detach the local copy of the document from the shared workspace without removing the shared copy.

Example

The following example determines whether the active document is connected to a shared workspace, then offers the user the option of removing the document from the workspace site.

VBA Copy code Copy code
    Dim r As Long
    If ActiveWorkbook.SharedWorkspace.Connected Then
        r = MsgBox("Are you sure you want to remove this document?", _
            vbQuestion + vbOKCancel, "Are you sure?")
        If r = vbOK Then
            ActiveWorkbook.SharedWorkspace.RemoveDocument
            MsgBox "The document is removed.", _
                vbInformation + vbOKOnly, "Removed"
        Else
            MsgBox "Removal canceled.", _
                vbInformation + vbOKOnly, "Still In Workspace"
        End If
    Else
        MsgBox "The active document is not connected to a shared workspace.", _
            vbInformation + vbOKOnly, "Not Connected"
    End If

See also

Concepts

SharedWorkspace Object

Other resources

SharedWorkspace Object Members


SharedWorkspaceFile Object (Office)

 Copy code hover
[image]

SharedWorkspaceFile Object (Office)
See also Send feedback

Published: July 09, 2012

The SharedWorkspaceFile object represents a file saved in a shared document workspace.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Remarks

Use the SharedWorkspaceFile object to manage documents and files saved in a shared workspace.

Example

Although the SharedWorkspaceFile object has a URL property that returns the file's complete path and filename, it does not have a FileName property. Use a simple function to extract the filename from the file's URL as in the following example. An additional supporting function decodes escaped space characters in the URL.

Copy code Copy code
Private Function FilenameFromURL(FileURL As String) As String
    Dim intLastSeparator As Integer
    FileURL = URLDecode(FileURL)
    intLastSeparator = InStrRev(FileURL, "/")
    FilenameFromURL = Right(FileURL, Len(FileURL) - intLastSeparator)
End Function

Private Function URLDecode(URLtoDecode As String) As String
    URLDecode = Replace(URLtoDecode, "%20", " ")
End Function

Use the Item(index) property of the SharedWorkspaceFiles collection to return a specific SharedWorkspaceFile object. Use the CreatedBy, CreatedDate, ModifiedBy, and ModifiedDate properties to return information about the history of each file. The following example returns the number of files in the shared workspace and information about each file, using the supporting functions shown above.

Copy code Copy code
    Dim swsFile As Office.SharedWorkspaceFile
    Dim strFileInfo As String
    strFileInfo = "The shared workspace contains " & _
    ActiveWorkbook.SharedWorkspace.Files.Count & " File(s)." & vbCrLf
    For Each swsFile In ActiveWorkbook.SharedWorkspace.Files
        strFileInfo = strFileInfo & FilenameFromURL(swsFile.URL) & vbCrLf & _
            " - URL: " & swsFile.URL & vbCrLf & _
            " - Created by: " & swsFile.CreatedBy & vbCrLf & _
            " - Created on: " & swsFile.CreatedDate & vbCrLf & _
            " - Modified by: " & swsFile.ModifiedBy & vbCrLf & _
            " - Modified on: " & swsFile.ModifiedDate & vbCrLf
    Next
    MsgBox strFileInfo, vbInformation + vbOKOnly, _
        "Files in Shared Workspace"
    Set swsFile = Nothing

See also

Concepts

Object Model Reference

Other resources

SharedWorkspaceFile Object Members


SharedWorkspaceFile Members (Office)

 Copy code hover
[image]

SharedWorkspaceFile Members (Office)
Send feedback

Published: July 09, 2012

The SharedWorkspaceFile object represents a file saved in a shared document workspace.

Methods

Name | Description
Delete | Deletes the current SharedWorkspaceFile object.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.
CreatedBy | Gets the display name of the member who created the shared workspace object. Read-only.
CreatedDate | Gets the date and time when the shared workspace object was created. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFile object was created. Read-only.
ModifiedBy | Gets the name of the user who last modified the object. Read-only.
ModifiedDate | Gets the date and time when the SharedWorkspaceFile object was last modified. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceFile object. Read-only.
URL | Gets the full Uniform Resource Locator (URL) and file name of the shared workspace file. Read-only.


SharedWorkspaceFile Properties (Office)

 Copy code hover
[image]

SharedWorkspaceFile Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.
CreatedBy | Gets the display name of the member who created the shared workspace object. Read-only.
CreatedDate | Gets the date and time when the shared workspace object was created. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFile object was created. Read-only.
ModifiedBy | Gets the name of the user who last modified the object. Read-only.
ModifiedDate | Gets the date and time when the SharedWorkspaceFile object was last modified. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceFile object. Read-only.
URL | Gets the full Uniform Resource Locator (URL) and file name of the shared workspace file. Read-only.


SharedWorkspaceFile.Application Property (Office)

 Copy code hover
[image]

SharedWorkspaceFile.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a SharedWorkspaceFile object.

Return Value

Object

See also

Concepts

SharedWorkspaceFile Object

Other resources

SharedWorkspaceFile Object Members


SharedWorkspaceFile.CreatedBy Property (Office)

 Copy code hover
[image]

SharedWorkspaceFile.CreatedBy Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the display name of the member who created the shared workspace object. Read-only.

Syntax

expression .CreatedBy

expression A variable that represents a SharedWorkspaceFile object.

Return Value

String

Example

The following example lists files in the shared workspace site that were created by users other than the creator of the workspace site.

VBA Copy code Copy code
 Dim swsFile As Office.SharedWorkspaceFile
 Dim swsOwner As Office.SharedWorkspaceMember
 Dim strMemberFiles As String
 Set swsOwner = ActiveWorkbook.SharedWorkspace.Members(1)
 For Each swsFile In ActiveWorkbook.SharedWorkspace.Files
 If swsFile.CreatedBy <> swsOwner.Name Then
 strMemberFiles = strMemberFiles & swsFile.URL & vbCrLf
 End If
 Next
 MsgBox "These files were created by other users:" & _
 vbCrLf & strMemberFiles, _
 vbInformation + vbOKOnly, "Files Created by Other Users"
 Set swsOwner = Nothing
 Set swsFile = Nothing
Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

See also

Concepts

SharedWorkspaceFile Object

Other resources

SharedWorkspaceFile Object Members


SharedWorkspaceFile.CreatedDate Property (Office)

 Copy code hover
[image]

SharedWorkspaceFile.CreatedDate Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the date and time when the shared workspace object was created. Read-only.

Syntax

expression .CreatedDate

expression A variable that represents a SharedWorkspaceFile object.

Return Value

Variant

Example

The following example returns a list of shared workspace files whose date and time created is earlier than today.

VBA Copy code Copy code
 Dim swsFile As Office.SharedWorkspaceFile
 Dim dtmMidnight As Date
 Dim dtmFileDate As Date
 Dim strOlderFiles As String
 dtmMidnight = CDate(FormatDateTime(Now, vbShortDate) & " 12:00:00 am")
 For Each swsFile In ActiveWorkbook.SharedWorkspace.Files
 dtmFileDate = swsFile.CreatedDate
 If dtmFileDate < dtmMidnight Then
 strOlderFiles = strOlderFiles & swsFile.URL & vbCrLf
 End If
 Next
 MsgBox "Files older than today: " & vbCrLf & strOlderFiles, _
 vbInformation + vbOKOnly, "Older Files"
 Set swsFile = Nothing
Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

See also

Concepts

SharedWorkspaceFile Object

Other resources

SharedWorkspaceFile Object Members


SharedWorkspaceFile.Creator Property (Office)

 Copy code hover
[image]

SharedWorkspaceFile.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFile object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a SharedWorkspaceFile object.

Return Value

Long

Remarks

As an example, if the object was created in Microsoft Word, this property returns 1297307460, which represents the string "MSWD"; in Microsoft Excel, this property returns 1480803660. This value can also be represented by the constant wdCreatorCode in Word, or xlCreatorCode in Excel. The Creator property was primarily designed to be used on the Macintosh, where each application has a four-character creator code. For example, Microsoft Word has the creator code MSWD. For additional information about this property, consult the language reference Help included with Microsoft Office Macintosh Edition.

The Creator property always returns the numeric identifier for the active application, just as the Application property always returns the name of the active applicatin in string form. Use the CreatedBy property of the SharedWorkspaceFile object to return the name of the individual who created the object. Use document properties to return information about the authors of Office documents.

See also

Concepts

SharedWorkspaceFile Object

Other resources

SharedWorkspaceFile Object Members


SharedWorkspaceFile.ModifiedBy Property (Office)

 Copy code hover
[image]

SharedWorkspaceFile.ModifiedBy Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the user who last modified the object. Read-only.

Syntax

expression .ModifiedBy

expression A variable that represents a SharedWorkspaceFile object.

Return Value

String

Remarks

For shared workspace objects, the ModifiedBy property returns the display name stored in the Name property of the SharedWorkspaceMember object.

Example

The following example lists the files in a shared workspace site that were last modified by users other than the creator of the workspace site.

Copy code Copy code
 Dim swsFile As Office.SharedWorkspaceFile
 Dim swsOwner As Office.SharedWorkspaceMember
 Dim strMemberFiles As String
 Set swsOwner = ActiveWorkbook.SharedWorkspace.Members(1)
 For Each swsFile In ActiveWorkbook.SharedWorkspace.Files
 If swsFile.ModifiedBy <> swsOwner.Name Then
 strMemberFiles = strMemberFiles & swsFile.URL & vbCrLf
 End If
 Next
 MsgBox "These files were last modified by other users:" & _
 vbCrLf & strMemberFiles, _
 vbInformation + vbOKOnly, "Files Modified by Other Users"
 Set swsOwner = Nothing
 Set swsFile = Nothing
Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

See also

Concepts

SharedWorkspaceFile Object

Other resources

SharedWorkspaceFile Object Members


SharedWorkspaceFile.ModifiedDate Property (Office)

 Copy code hover
[image]

SharedWorkspaceFile.ModifiedDate Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the date and time when the SharedWorkspaceFile object was last modified. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ModifiedDate

expression A variable that represents a SharedWorkspaceFile object.

Return Value

Variant

Example

The following example returns a list of shared workspace files whose date and time last modified is earlier than today.

VBA Copy code Copy code
Dim swsFile As Office.SharedWorkspaceFile
    Dim dtmMidnight As Date
    Dim dtmFileDate As Date
    Dim strOlderFiles As String
    dtmMidnight = CDate(FormatDateTime(Now, vbShortDate) & " 12:00:00 am")
    For Each swsFile In ActiveWorkbook.SharedWorkspace.Files
        dtmFileDate = swsFile.ModifiedDate
        If dtmFileDate < dtmMidnight Then
            strOlderFiles = strOlderFiles & swsFile.URL & vbCrLf
        End If
    Next
    MsgBox "Files not modified today: " & vbCrLf & strOlderFiles, _
        vbInformation + vbOKOnly, "Older Files"
    Set swsFile = Nothing

See also

Concepts

SharedWorkspaceFile Object

Other resources

SharedWorkspaceFile Object Members


SharedWorkspaceFile.Parent Property (Office)

 Copy code hover
[image]

SharedWorkspaceFile.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the SharedWorkspaceFile object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a SharedWorkspaceFile object.

Return Value

Object

See also

Concepts

SharedWorkspaceFile Object

Other resources

SharedWorkspaceFile Object Members


SharedWorkspaceFile.URL Property (Office)

 Copy code hover
[image]

SharedWorkspaceFile.URL Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the full Uniform Resource Locator (URL) and file name of the shared workspace file. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .URL

expression A variable that represents a SharedWorkspaceFile object.

Return Value

String

Remarks

The URL property returns the address of the shared workspace file in this format: http://server/sites/user/workspace/Shared%Documents/MyWorkbook.xls. The URL property returns a URL-encoded string. For example, a space in the folder name is represented by %20. The SharedWorkspaceFile object does not have a Name or FileName property. The filename must be extracted from the URL property.

Example

The following example displays the URL of the shared workspace file.

Copy code Copy code
MsgBox "URL: " & ActiveWorkbook.SharedWorkspaceFile.URL, _
        vbInformation + vbOKOnly, "Shared Workspace File URL"

See also

Concepts

SharedWorkspaceFile Object

Other resources

SharedWorkspaceFile Object Members


SharedWorkspaceFile Methods (Office)

 Copy code hover
[image]

SharedWorkspaceFile Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes the current SharedWorkspaceFile object.


SharedWorkspaceFile.Delete Method (Office)

 Copy code hover
[image]

SharedWorkspaceFile.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the current SharedWorkspaceFile object.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Delete

expression Required. A variable that represents a SharedWorkspaceFile object.

See also

Concepts

SharedWorkspaceFile Object

Other resources

SharedWorkspaceFile Object Members


SharedWorkspaceFiles Object (Office)

 Copy code hover
[image]

SharedWorkspaceFiles Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of the SharedWorkspaceFile objects in the current shared workspace.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Example

Use the Files property of the SharedWorkspace object to return a SharedWorkspaceFiles collection.

Copy code Copy code
    Dim swsFiles As Office.SharedWorkspaceFiles
    Set swsFiles = ActiveWorkbook.SharedWorkspace.Files
    MsgBox "There are " & swsFiles.Count & _
        " file(s)
        vbInformation + vbOKOnly, _
        "Collection Information"
    Set swsFiles = Nothing

See also

Concepts

Object Model Reference

Other resources

SharedWorkspaceFiles Object Members


SharedWorkspaceFiles Members (Office)

 Copy code hover
[image]

SharedWorkspaceFiles Members (Office)
Send feedback

Published: July 09, 2012

A collection of the SharedWorkspaceFile objects in the current shared workspace.

Methods

Name | Description
Add | Adds a file to the document library in a shared workspace. Returns a SharedWorkspaceFile object.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SharedWorkspaceFiles collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFiles object was created. Read-only.
Item | Gets a SharedWorkspaceFile object from the Files collection of the shared workspace. Read-only.
ItemCountExceeded | Gets a Boolean value indicating whether the number of files allowed in the shared workspace has been exceeded. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceFiles object. Read-only.


SharedWorkspaceFiles Properties (Office)

 Copy code hover
[image]

SharedWorkspaceFiles Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SharedWorkspaceFiles collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFiles object was created. Read-only.
Item | Gets a SharedWorkspaceFile object from the Files collection of the shared workspace. Read-only.
ItemCountExceeded | Gets a Boolean value indicating whether the number of files allowed in the shared workspace has been exceeded. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceFiles object. Read-only.


SharedWorkspaceFiles.Application Property (Office)

 Copy code hover
[image]

SharedWorkspaceFiles.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a SharedWorkspaceFiles object.

Return Value

Object

See also

Concepts

SharedWorkspaceFiles Object

Other resources

SharedWorkspaceFiles Object Members


SharedWorkspaceFiles.Count Property (Office)

 Copy code hover
[image]

SharedWorkspaceFiles.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the SharedWorkspaceFiles collection. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Count

expression A variable that represents a SharedWorkspaceFiles object.

Return Value

Long

See also

Concepts

SharedWorkspaceFiles Object

Other resources

SharedWorkspaceFiles Object Members


SharedWorkspaceFiles.Creator Property (Office)

 Copy code hover
[image]

SharedWorkspaceFiles.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFiles object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a SharedWorkspaceFiles object.

Return Value

Long

Remarks

As an example, if the object was created in Microsoft Word, this property returns 1297307460, which represents the string "MSWD"; in Microsoft Excel, this property returns 1480803660. This value can also be represented by the constant wdCreatorCode in Word, or xlCreatorCode in Excel. The Creator property was primarily designed to be used on the Macintosh, where each application has a four-character creator code. For example, Microsoft Word has the creator code MSWD. For additional information about this property, consult the language reference Help included with Microsoft Office Macintosh Edition.

The Creator property always returns the numeric identifier for the active application, just as the Application property always returns the name of the active applicatin in string form. Use the CreatedBy property of the SharedWorkspaceFile object to return the name of the individual who created the object. Use document properties to return information about the authors of Office documents.

See also

Concepts

SharedWorkspaceFiles Object

Other resources

SharedWorkspaceFiles Object Members


SharedWorkspaceFiles.Item Property (Office)

 Copy code hover
[image]

SharedWorkspaceFiles.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a SharedWorkspaceFile object from the Files collection of the shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Item(Index)

expression Required. A variable that represents a SharedWorkspaceFiles object. The specified SharedWorkspaceFiles collection.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | Returns the SharedWorkspaceFile at the position specified. The returned SharedWorkspaceFile object does not correspond to the order in which the items are displayed in the Shared Workspace pane, and is not affected by re-sorting the display.

See also

Concepts

SharedWorkspaceFiles Object

Other resources

SharedWorkspaceFiles Object Members


SharedWorkspaceFiles.ItemCountExceeded Property (Office)

 Copy code hover
[image]

SharedWorkspaceFiles.ItemCountExceeded Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value indicating whether the number of files allowed in the shared workspace has been exceeded. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ItemCountExceeded

expression An expression that returns a SharedWorkspaceFiles object.

Return Value

Boolean

See also

Concepts

SharedWorkspaceFiles Object

Other resources

SharedWorkspaceFiles Object Members


SharedWorkspaceFiles.Parent Property (Office)

 Copy code hover
[image]

SharedWorkspaceFiles.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the SharedWorkspaceFiles object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a SharedWorkspaceFiles object.

Return Value

Object

See also

Concepts

SharedWorkspaceFiles Object

Other resources

SharedWorkspaceFiles Object Members


SharedWorkspaceFiles Methods (Office)

 Copy code hover
[image]

SharedWorkspaceFiles Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a file to the document library in a shared workspace. Returns a SharedWorkspaceFile object.


SharedWorkspaceFiles.Add Method (Office)

 Copy code hover
[image]

SharedWorkspaceFiles.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a file to the document library in a shared workspace. Returns a SharedWorkspaceFile object.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Add(FileName, ParentFolder, OverwriteIfFileAlreadyExists, KeepInSync)

expression Required. A variable that represents a SharedWorkspaceFiles object.

Parameters

Name | Required/Optional | Data Type | Description
FileName | Required | String | The path and filename of the file to be added to the current shared workspace.
ParentFolder | Optional | SharedWorkspaceFolder | The subfolder in which to place the file, if not the main document library folder within the shared workspace. Add the file to the main document library folder by leaving this optional argument empty.
OverwriteIfFileAlreadyExists | Optional | Boolean | True to overwrite an existing file by the same name. Default is False.
KeepInSync | Optional | Boolean | True to keep the local copy of the document synchronized with the copy in the shared workspace. Default is False.

Example

The following example adds a new file to the files collection of the shared workspace.

VBA Copy code Copy code
    Dim swsfile As Office.SharedWorkspaceFile
    Set swsfile = ActiveWorkbook.SharedWorkspace.Files.Add( _
        "C:\MyWorkbook.xls", _
        , True, True)
    MsgBox "New file URL: " & swsfile.URL, _
        vbInformation + vbOKOnly, _
        "New File in Shared Workspace Files"
    Set swsfile = Nothing

See also

Concepts

SharedWorkspaceFiles Object

Other resources

SharedWorkspaceFiles Object Members


SharedWorkspaceFolder Object (Office)

 Copy code hover
[image]

SharedWorkspaceFolder Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a folder in a shared document workspace.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Remarks

Use the SharedWorkspaceFolder object to manage subfolders within the main document library folder of a shared workspace.

The Count property of the SharedWorkspaceFolders collection does not include the workspace's main folder and returns 0 (zero) if no subfolders have been created.

The SharedWorkspaceFolder object does not expose the CreatedBy, CreatedDate , ModifiedBy, and ModifiedDate properties available on the SharedWorkspaceFile, SharedWorkspaceLink, and SharedWorkspaceTask objects.

Use the Item(index) property of the SharedWorkspaceFolders collection to return a specific SharedWorkspaceFolder object.

Example

Use the FolderName property to return the name of the shared workspace folder. The following example returns the name of the first subfolder in the SharedWorkspaceFolders collection in the format "parentfoldername/foldername."

Copy code Copy code
    Dim swsFolder As SharedWorkspaceFolder
    Set swsFolder = ActiveWorkbook.SharedWorkspace.Folders(1)
    MsgBox swsFolder.FolderName, vbInformation + vbOKOnly, "Folder Name"
    Set swsFolder = Nothing

See also

Concepts

Object Model Reference

Other resources

SharedWorkspaceFolder Object Members


SharedWorkspaceFolder Members (Office)

 Copy code hover
[image]

SharedWorkspaceFolder Members (Office)
Send feedback

Published: July 09, 2012

Represents a folder in a shared document workspace.

Methods

Name | Description
Delete | Deletes the current shared workspace folder and all data within it.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceFolder object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFolder object was created. Read-only.
FolderName | Gets the name of a subfolder within the main document library folder of a shared workspace. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceFolder object. Read-only.


SharedWorkspaceFolder Properties (Office)

 Copy code hover
[image]

SharedWorkspaceFolder Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceFolder object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFolder object was created. Read-only.
FolderName | Gets the name of a subfolder within the main document library folder of a shared workspace. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceFolder object. Read-only.


SharedWorkspaceFolder.Application Property (Office)

 Copy code hover
[image]

SharedWorkspaceFolder.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SharedWorkspaceFolder object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a SharedWorkspaceFolder object.

Return Value

Object

See also

Concepts

SharedWorkspaceFolder Object

Other resources

SharedWorkspaceFolder Object Members


SharedWorkspaceFolder.Creator Property (Office)

 Copy code hover
[image]

SharedWorkspaceFolder.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFolder object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a SharedWorkspaceFolder object.

Return Value

Long

Remarks

As an example, if the object was created in Microsoft Word, this property returns 1297307460, which represents the string "MSWD"; in Microsoft Excel, this property returns 1480803660. This value can also be represented by the constant wdCreatorCode in Word, or xlCreatorCode in Excel. The Creator property was primarily designed to be used on the Macintosh, where each application has a four-character creator code. For example, Microsoft Word has the creator code MSWD. For additional information about this property, consult the language reference Help included with Microsoft Office Macintosh Edition.

The Creator property always returns the numeric identifier for the active application, just as the Application property always returns the name of the active applicatin in string form. Used the CreatedBy property of theSharedWorkspaceFolder object to return the name of the individual who created the object. Use document properties to return information about the authors of Office documents.

See also

Concepts

SharedWorkspaceFolder Object

Other resources

SharedWorkspaceFolder Object Members


SharedWorkspaceFolder.FolderName Property (Office)

 Copy code hover
[image]

SharedWorkspaceFolder.FolderName Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of a subfolder within the main document library folder of a shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .FolderName

expression A variable that represents a SharedWorkspaceFolder object.

Remarks

The FolderName property returns the subfolder name in the format parentfolder/subfolder. For example, if the shared workspace contains a folder named "Supporting Documents", the FolderName property returns Shared Documents/Supporting Documents.

Example

The following example displays the number of subfolders in the shared workspace and their names.

Copy code Copy code
    Dim swsFolder As Office.SharedWorkspaceFolder
    Dim strFolderInfo As String
    strFolderInfo = "The shared workspace contains " & _
        ActiveWorkbook.SharedWorkspace.Folders.Count & " folder(s)." & vbCrLf
    If ActiveWorkbook.SharedWorkspace.Folders.Count > 0 Then
        For Each swsFolder In ActiveWorkbook.SharedWorkspace.Folders
            strFolderInfo = strFolderInfo & swsFolder.FolderName & vbCrLf
        Next
    End If
    MsgBox strFolderInfo, vbInformation + vbOKOnly, _
        "Folders in Shared Workspace"
    Set swsFolder = Nothing

See also

Concepts

SharedWorkspaceFolder Object

Other resources

SharedWorkspaceFolder Object Members


SharedWorkspaceFolder.Parent Property (Office)

 Copy code hover
[image]

SharedWorkspaceFolder.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the SharedWorkspaceFolder object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a SharedWorkspaceFolder object.

Return Value

Object

See also

Concepts

SharedWorkspaceFolder Object

Other resources

SharedWorkspaceFolder Object Members


SharedWorkspaceFolder Methods (Office)

 Copy code hover
[image]

SharedWorkspaceFolder Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes the current shared workspace folder and all data within it.


SharedWorkspaceFolder.Delete Method (Office)

 Copy code hover
[image]

SharedWorkspaceFolder.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the current shared workspace folder and all data within it.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Delete(DeleteEvenIfFolderContainsFiles)

expression Required. A variable that represents a SharedWorkspaceFolder object.

Parameters

Name | Required/Optional | Data Type | Description
DeleteEvenIfFolderContainsFiles | Optional | Boolean | True to delete the folder without warning even if the folder contains files. Default is False.The Delete method will fail if the user does not have permission to delete the current folder from the shared workspace.

See also

Concepts

SharedWorkspaceFolder Object

Other resources

SharedWorkspaceFolder Object Members


SharedWorkspaceFolders Object (Office)

 Copy code hover
[image]

SharedWorkspaceFolders Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of the SharedWorkspaceFolder objects in the current shared workspace.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Example

Use the Folders property of the SharedWorkspace object to return a SharedWorkspaceFolders collection.

Copy code Copy code
    Dim swsFolders As Office.SharedWorkspaceFolders
    Set swsFolders = ActiveWorkbook.SharedWorkspace.Folders
    MsgBox "There are " & swsFolders.Count & _
        " folder(s) in the current shared workspace.", _
        vbInformation + vbOKOnly, _
        "Collection Information"
    Set swsFolders = Nothing

See also

Concepts

Object Model Reference

Other resources

SharedWorkspaceFolders Object Members


SharedWorkspaceFolders Members (Office)

 Copy code hover
[image]

SharedWorkspaceFolders Members (Office)
Send feedback

Published: July 09, 2012

A collection of the SharedWorkspaceFolder objects in the current shared workspace.

Methods

Name | Description
Add | Adds a folder to the document library in a shared workspace. Returns a SharedWorkspaceFolder object.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SharedWorkspaceFolders collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFolders object was created. Read-only.
Item | Gets a SharedWorkspaceFolder object from the Folders collection of the shared workspace. Read-only.
ItemCountExceeded | Gets a Boolean value that indicates whether the number of SharedWorkspaceFolders items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceFolders object. Read-only.


SharedWorkspaceFolders Properties (Office)

 Copy code hover
[image]

SharedWorkspaceFolders Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SharedWorkspaceFolders collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFolders object was created. Read-only.
Item | Gets a SharedWorkspaceFolder object from the Folders collection of the shared workspace. Read-only.
ItemCountExceeded | Gets a Boolean value that indicates whether the number of SharedWorkspaceFolders items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceFolders object. Read-only.


SharedWorkspaceFolders.Application Property (Office)

 Copy code hover
[image]

SharedWorkspaceFolders.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a SharedWorkspaceFolders object.

Return Value

Object

See also

Concepts

SharedWorkspaceFolders Object

Other resources

SharedWorkspaceFolders Object Members


SharedWorkspaceFolders.Count Property (Office)

 Copy code hover
[image]

SharedWorkspaceFolders.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the SharedWorkspaceFolders collection. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Count

expression A variable that represents a SharedWorkspaceFolders object.

Return Value

Long

See also

Concepts

SharedWorkspaceFolders Object

Other resources

SharedWorkspaceFolders Object Members


SharedWorkspaceFolders.Creator Property (Office)

 Copy code hover
[image]

SharedWorkspaceFolders.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SharedWorkspaceFolders object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a SharedWorkspaceFolders object.

Return Value

Long

Remarks

As an example, if the object was created in Microsoft Word, this property returns 1297307460, which represents the string "MSWD"; in Microsoft Excel, this property returns 1480803660. This value can also be represented by the constant wdCreatorCode in Word, or xlCreatorCode in Excel. The Creator property was primarily designed to be used on the Macintosh, where each application has a four-character creator code. For example, Microsoft Word has the creator code MSWD. For additional information about this property, consult the language reference Help included with Microsoft Office Macintosh Edition.

The Creator property always returns the numeric identifier for the active application, just as the Application property always retobjmemName> object to return the name of the individual who created the object. Use document properties to return information about the authors of Office documents.

See also

Concepts

SharedWorkspaceFolders Object

Other resources

SharedWorkspaceFolders Object Members


SharedWorkspaceFolders.Item Property (Office)

 Copy code hover
[image]

SharedWorkspaceFolders.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a SharedWorkspaceFolder object from the Folders collection of the shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Item(Index)

expression Required. A variable that represents a SharedWorkspaceFolders object. The specified SharedWorkspaceFolders collection.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | Returns the SharedWorkspaceFolder at the position specified. The returned SharedWorkspaceFolder object does not correspond to the order in which the items are displayed in the Shared Workspace pane, and is not affected by re-sorting the display.

See also

Concepts

SharedWorkspaceFolders Object

Other resources

SharedWorkspaceFolders Object Members


SharedWorkspaceFolders.ItemCountExceeded Property (Office)

 Copy code hover
[image]

SharedWorkspaceFolders.ItemCountExceeded Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value that indicates whether the number of SharedWorkspaceFolders items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ItemCountExceeded

expression A variable that represents a SharedWorkspaceFolders object.

Return Value

Boolean

Remarks

The Shared Workspace task pane can only display 99 shared workspace files and folders, links, members, or tasks. If more than 99 items are added to any of these collections: the corresponding tab of the Shared Workspace task pane will stop displaying the list of items and displays a link to the shared workspace site Web page instead; the collection is no longer populated locally and its Count property returns 0 (zero).

Furthermore, once the ItemCountExceeded property returns True for one of the collections listed above, the developer can no longer remedy the situation programmatically by deleting items from the collection to reduce the count below 99, because the collection is no longer populated.

The ItemCountExceeded property of the SharedWorkspaceFolders collection returns True when the combined count of files and folders exceeds 99, since both lists are combined and displayed together on the Documents tab of the Shared Workspace task pane.

See also

Concepts

SharedWorkspaceFolders Object

Other resources

SharedWorkspaceFolders Object Members


SharedWorkspaceFolders.Parent Property (Office)

 Copy code hover
[image]

SharedWorkspaceFolders.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the SharedWorkspaceFolders object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a SharedWorkspaceFolders object.

Return Value

Object

See also

Concepts

SharedWorkspaceFolders Object

Other resources

SharedWorkspaceFolders Object Members


SharedWorkspaceFolders Methods (Office)

 Copy code hover
[image]

SharedWorkspaceFolders Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a folder to the document library in a shared workspace. Returns a SharedWorkspaceFolder object.


SharedWorkspaceFolders.Add Method (Office)

 Copy code hover
[image]

SharedWorkspaceFolders.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a folder to the document library in a shared workspace. Returns a SharedWorkspaceFolder object.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Add(FolderName, ParentFolder)

expression Required. A variable that represents a SharedWorkspaceFolders object.

Parameters

Name | Required/Optional | Data Type | Description
FolderName | Required | String | The name of the folder to be added to the current shared workspace.
ParentFolder | Optional | SharedWorkspaceFolder | The subfolder in which to place the new folder, if not the main document library folder within the shared workspace. Add the folder to the main document library folder by leaving this optional argument empty.

Example

The following example adds a new folder to the folders collection of the shared workspace.

VBA Copy code Copy code
    Dim swsFolder As Office.SharedWorkspaceFolder
    Set swsFolder = ActiveWorkbook.SharedWorkspace.Folders.Add("MyNewFolder")
    MsgBox "New folder: " & swsFolder.FolderName, _
        vbInformation + vbOKOnly, _
        "New Folder in Shared Workspace"
    Set swsFolder = Nothing

See also

Concepts

SharedWorkspaceFolders Object

Other resources

SharedWorkspaceFolders Object Members


SharedWorkspaceLink Object (Office)

 Copy code hover
[image]

SharedWorkspaceLink Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a URL link saved in a shared document workspace site.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Remarks

Use the SharedWorkspaceLink object to manage links to additional documents and information of interest to the members who are collaborating on the documents in the shared workspace site.

Use the Item(index) property of the SharedWorkspaceLinks collection to return a specific SharedWorkspaceLink object.

Use the Description property to set the link description that appears on the Links tab of the Shared Workspace pane and on the workspace Web page. Use the URL property to set the destination address of the link. Use the Notes property to supply additional information about the link.

Use the Save method to upload changes to the server after you modify properties of the SharedWorkspaceLink object.

Use the CreatedBy, CreatedDate, ModifiedBy, and ModifiedDate properties to return information about the history of each link.

Example

The following example modifies the first link in the shared workspace site to point to the Microsoft Developer Network home page, then uploads the changes to the server.

Copy code Copy code
    Dim swsLink As Office.SharedWorkspaceLink
    Set swsLink = ActiveWorkbook.SharedWorkspace.Links(1)
    With swsLink
        .Description = "MSDN Home Page"
        .URL = "http://msdn.microsoft.com/"
        .Notes = "My favorite site for developers!"
        .Save
    End With
    Set swsLink = Nothing

See also

Concepts

Object Model Reference

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink Members (Office)

 Copy code hover
[image]

SharedWorkspaceLink Members (Office)
Send feedback

Published: July 09, 2012

Represents a URL link saved in a shared document workspace site.

Methods

Name | Description
Delete | Deletes the current SharedWorkspaceLink object.
Save | Uploads changes made programmatically to a shared server.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.
CreatedBy | Gets the display name of the member who created the shared workspace object. Read-only.
CreatedDate | Gets the date and time when the shared workspace object was created. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceLink object was created. Read-only.
Description | Gets or sets a descriptive String value for the specified SharedWorkspaceLink or SharedWorkspaceTask object. Read/write.
ModifiedBy | Gets the name of the user who last modified the object. Read-only.
ModifiedDate | Gets the date and time when the SharedWorkspaceLink object was last modified. Read-only.
Notes | Gets or sets the optional notes associated with a shared workspace link. Read/write.
Parent | Gets the Parent object for the SharedWorkspaceLink object. Read-only.
URL | Gets the top-level Uniform Resource Locator (URL) of the shared workspace link. Read/write.


SharedWorkspaceLink Properties (Office)

 Copy code hover
[image]

SharedWorkspaceLink Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.
CreatedBy | Gets the display name of the member who created the shared workspace object. Read-only.
CreatedDate | Gets the date and time when the shared workspace object was created. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceLink object was created. Read-only.
Description | Gets or sets a descriptive String value for the specified SharedWorkspaceLink or SharedWorkspaceTask object. Read/write.
ModifiedBy | Gets the name of the user who last modified the object. Read-only.
ModifiedDate | Gets the date and time when the SharedWorkspaceLink object was last modified. Read-only.
Notes | Gets or sets the optional notes associated with a shared workspace link. Read/write.
Parent | Gets the Parent object for the SharedWorkspaceLink object. Read-only.
URL | Gets the top-level Uniform Resource Locator (URL) of the shared workspace link. Read/write.


SharedWorkspaceLink.Application Property (Office)

 Copy code hover
[image]

SharedWorkspaceLink.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SharedWorkspaceFile object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a SharedWorkspaceLink object.

Return Value

Object

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink.CreatedBy Property (Office)

 Copy code hover
[image]

SharedWorkspaceLink.CreatedBy Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the display name of the member who created the shared workspace object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .CreatedBy

expression A variable that represents a SharedWorkspaceLink object.

Return Value

String

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink.CreatedDate Property (Office)

 Copy code hover
[image]

SharedWorkspaceLink.CreatedDate Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the date and time when the shared workspace object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .CreatedDate

expression A variable that represents a SharedWorkspaceLink object.

Return Value

Variant

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink.Creator Property (Office)

 Copy code hover
[image]

SharedWorkspaceLink.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SharedWorkspaceLink object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a SharedWorkspaceLink object.

Return Value

Long

Remarks

As an example, if the object was created in Microsoft Word, this property returns 1297307460, which represents the string "MSWD"; in Microsoft Excel, this property returns 1480803660. This value can also be represented by the constant wdCreatorCode in Word, or xlCreatorCode in Excel. The Creator property was primarily designed to be used on the Macintosh, where each application has a four-character creator code. For example, Microsoft Word has the creator code MSWD. For additional information about this property, consult the language reference Help included with Microsoft Office Macintosh Edition.

The Creator property always returns the numeric identifier for the active application, just as the Application property always returns the name of the active applicatin in string form. Use the CreatedBy property of the SharedWorkspaceLink object to return the name of the individual who created the object. Use document properties to return information about the authors of Office documents.

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink.Description Property (Office)

 Copy code hover
[image]

SharedWorkspaceLink.Description Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a descriptive String value for the specified SharedWorkspaceLink or SharedWorkspaceTask object. Read/write.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Description

expression Required. A variable that represents a SharedWorkspaceLink object.

Remarks

The Description property is optional when a new shared workspace link or task is created, and may be empty.

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink.ModifiedBy Property (Office)

 Copy code hover
[image]

SharedWorkspaceLink.ModifiedBy Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the user who last modified the object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ModifiedBy

expression A variable that represents a SharedWorkspaceLink object.

Return Value

String

Remarks

For shared workspace objects, the ModifiedBy property returns the display name stored in the Name property of the SharedWorkspaceMember object.

Example

The following example lists the links in a shared workspace site that were modified by a particular users.

Copy code Copy code
    Dim swsLink As Office.SharedWorkspaceLink
    Dim swsOwner As Office.SharedWorkspaceMember
    Dim strMemberFiles As String
    Dim strUser As String
    strUser = "Nancy Davolio"
    Set swsOwner = ActiveWorkbook.SharedWorkspace.Members(1)
    For Each swsLink In ActiveWorkbook.SharedWorkspace.Links
        If swsLink.ModifiedBy = strUser Then
            strMemberlinks = strMemberlinks & swsLink.URL & vbCrLf
        End If
    Next
    MsgBox "These links were modified by " & _
        strUser & vbCrLf & strMemberlinks, _
        vbInformation + vbOKOnly, "Modified Links"
    Set swsOwner = Nothing
    Set swsLink = Nothing

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink.ModifiedDate Property (Office)

 Copy code hover
[image]

SharedWorkspaceLink.ModifiedDate Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the date and time when the SharedWorkspaceLink object was last modified. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ModifiedDate

expression A variable that represents a SharedWorkspaceLink object.

Return Value

Variant

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink.Notes Property (Office)

 Copy code hover
[image]

SharedWorkspaceLink.Notes Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the optional notes associated with a shared workspace link. Read/write.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Notes

expression A variable that represents a SharedWorkspaceLink object.

Example

The following example creates a list of all the shared workspace links that contain the word "building" in the Notes field.

Copy code Copy code
Dim strBuildingLinks As String
Dim swsLink As Office.SharedWorkspaceLink
For Each swsLink In ActiveWorkbook.SharedWorkspace.Links
   If InStr(swsLink.Notes, "building", vbTextCompare) > 0 Then
      strBuildingLinks = strBuildingLinks & swsLink.Description & vbCrLf
   End If
Next
MsgBox "Building Links: " & vbCrLf & strBuildingLinks, _
   vbInformation + vbOKOnly, "Building Links in Shared Workspace"

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink.Parent Property (Office)

 Copy code hover
[image]

SharedWorkspaceLink.Parent Property (Office)
See also Send feedback

Gets the Parent object for the SharedWorkspaceLink object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a SharedWorkspaceLink object.

Return Value

Object

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink.URL Property (Office)

 Copy code hover
[image]

SharedWorkspaceLink.URL Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the top-level Uniform Resource Locator (URL) of the shared workspace link. Read/write.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .URL

expression A variable that represents a SharedWorkspaceLink object.

Return Value

String

Remarks

The URL property returns the address of the shared workspace in this format: http://server/sites/user/workspace/. The URL property returns a URL-encoded string. For example, a space in the folder name is represented by %20. Use a simple function like the following example to replace this escaped character with a space. Private Function URLDecode(URLtoDecode As String) As String URLDecode = Replace(URLtoDecode, "%20", " ") End Function

Example

The following example displays the URL of the link to the shared workspace.

Copy code Copy code
MsgBox "URL: " & ActiveWorkbook.SharedWorkspaceLink.URL, _
        vbInformation + vbOKOnly, "Shared Workspace Link URL"

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink Methods (Office)

 Copy code hover
[image]

SharedWorkspaceLink Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes the current SharedWorkspaceLink object.
Save | Uploads changes made programmatically to a shared server.


SharedWorkspaceLink.Delete Method (Office)

 Copy code hover
[image]

SharedWorkspaceLink.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the current SharedWorkspaceLink object.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Delete

expression Required. A variable that represents a SharedWorkspaceLink object.

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLink.Save Method (Office)

 Copy code hover
[image]

SharedWorkspaceLink.Save Method (Office)
See also Send feedback

Published: July 09, 2012

Uploads changes made programmatically to a shared server.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Save

expression A variable that represents a SharedWorkspaceLink object.

Parameters

Name | Required/Optional | Data Type | Description
bstrQueryName | Required | String | Name of the query used to change the shared workspace link.

Remarks

Use the Save method to upload changes to the server after changing the properties of a shared workspace link.

See also

Concepts

SharedWorkspaceLink Object

Other resources

SharedWorkspaceLink Object Members


SharedWorkspaceLinks Object (Office)

 Copy code hover
[image]

SharedWorkspaceLinks Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of the SharedWorkspaceLink objects in the current shared workspace.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Example

Use the Links property of the SharedWorkspace object to return a SharedWorkspaceLinks collection.

Copy code Copy code
    Dim swsLinks As Office.SharedWorkspaceLinks
    Set swsLinks = ActiveWorkbook.SharedWorkspace.Links
    MsgBox "There are " & swsLinks.Count & _
        " link(s) in the current shared workspace.", _
        vbInformation + vbOKOnly, _
        "Collection Information"
    Set swsLinks = Nothing

See also

Concepts

Object Model Reference

Other resources

SharedWorkspaceLinks Object Members


SharedWorkspaceLinks Members (Office)

 Copy code hover
[image]

SharedWorkspaceLinks Members (Office)
Send feedback

Published: July 09, 2012

A collection of the SharedWorkspaceLink objects in the current shared workspace.

Methods

Name | Description
Add | Adds a link to the list of links in a shared workspace.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceLinks object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SharedWorkspaceLinks object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceLinks object was created. Read-only.
Item | Gets a SharedWorkspaceLink object from the Links collection of the shared workspace. Read-only.
ItemCountExceeded | Gets a Boolean value that indicates whether the number of SharedWorkspaceLinks items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceLinks object. Read-only.


SharedWorkspaceLinks Properties (Office)

 Copy code hover
[image]

SharedWorkspaceLinks Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceLinks object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SharedWorkspaceLinks object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceLinks object was created. Read-only.
Item | Gets a SharedWorkspaceLink object from the Links collection of the shared workspace. Read-only.
ItemCountExceeded | Gets a Boolean value that indicates whether the number of SharedWorkspaceLinks items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceLinks object. Read-only.


SharedWorkspaceLinks.Application Property (Office)

 Copy code hover
[image]

SharedWorkspaceLinks.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SharedWorkspaceLinks object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a SharedWorkspaceLinks object.

Return Value

Object

See also

Concepts

SharedWorkspaceLinks Object

Other resources

SharedWorkspaceLinks Object Members


SharedWorkspaceLinks.Count Property (Office)

 Copy code hover
[image]

SharedWorkspaceLinks.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the SharedWorkspaceLinks object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Count

expression A variable that represents a SharedWorkspaceLinks object.

Return Value

Long

See also

Concepts

SharedWorkspaceLinks Object

Other resources

SharedWorkspaceLinks Object Members


SharedWorkspaceLinks.Creator Property (Office)

 Copy code hover
[image]

SharedWorkspaceLinks.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SharedWorkspaceLinks object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a SharedWorkspaceLinks object.

Return Value

Long

Remarks

As an example, if the object was created in Microsoft Word, this property returns 1297307460, which represents the string "MSWD"; in Microsoft Excel, this property returns 1480803660. This value can also be represented by the constant wdCreatorCode in Word, or xlCreatorCode in Excel. The Creator property was primarily designed to be used on the Macintosh, where each application has a four-character creator code. For example, Microsoft Word has the creator code MSWD. For additional information about this property, consult the language reference Help included with Microsoft Office Macintosh Edition.

The Creator property always returns the numeric identifier for the active application, just as the Application property always returns the name of the active applicatin in string form. Use the CreatedBy property of the SharedWorkspaceLink objects to return the name of the individual who created the object. Use document properties to return information about the authors of Office documents.

See also

Concepts

SharedWorkspaceLinks Object

Other resources

SharedWorkspaceLinks Object Members


SharedWorkspaceLinks.Item Property (Office)

 Copy code hover
[image]

SharedWorkspaceLinks.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a SharedWorkspaceLink object from the Links collection of the shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Item(Index)

expression Required. A variable that represents a SharedWorkspaceLinks object. The specified SharedWorkspaceLinks collection.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | Returns the SharedWorkspaceLink at the position specified. The returned SharedWorkspaceLink object does not correspond to the order in which the items are displayed in the Shared Workspace pane, and is not affected by re-sorting the display.

See also

Concepts

SharedWorkspaceLinks Object

Other resources

SharedWorkspaceLinks Object Members


SharedWorkspaceLinks.ItemCountExceeded Property (Office)

 Copy code hover
[image]

SharedWorkspaceLinks.ItemCountExceeded Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value that indicates whether the number of SharedWorkspaceLinks items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ItemCountExceeded

expression A variable that represents a SharedWorkspaceLinks object.

Return Value

Boolean

Remarks

The Shared Workspace task pane can only display 99 shared workspace files and folders, links, members, or tasks. If more than 99 items are added to any of these collections: the corresponding tab of the Shared Workspace task pane stops displaying the list of items and displays a link to the shared workspace site Web page instead; the collection is no longer populated locally and its Count property returns 0 (zero).

Furthermore, once the ItemCountExceeded property returns True for one of the collections listed above, the developer can no longer remedy the situation programmatically by deleting items from the collection to reduce the count below 99, because the collection is no longer populated.

Example

The following example checks the Count property of the SharedWorkspaceLinks collection. If Count returns 0 (zero), it checks the ItemCountExceeded property to determine whether in fact the shared workspace has no saved links, or whether it has more than 99 and the links collection has been cleared.

VBA Copy code Copy code
ActiveWorkbook.SharedWorkspace.Refresh
    If ActiveWorkbook.SharedWorkspace.Links.Count = 0 Then
        If ActiveWorkbook.SharedWorkspace.Links.ItemCountExceeded Then
            MsgBox "More than 99 links in shared workspace.", _
                vbInformation + vbOKOnly, "Item Count Exceeded"
        Else
            MsgBox "No links in shared workspace.", _
                vbInformation + vbOKOnly, "No Links"
        End If
    End If

See also

Concepts

SharedWorkspaceLinks Object

Other resources

SharedWorkspaceLinks Object Members


SharedWorkspaceLinks.Parent Property (Office)

 Copy code hover
[image]

SharedWorkspaceLinks.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the SharedWorkspaceLinks object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a SharedWorkspaceLinks object.

Return Value

Object

See also

Concepts

SharedWorkspaceLinks Object

Other resources

SharedWorkspaceLinks Object Members


SharedWorkspaceLinks Methods (Office)

 Copy code hover
[image]

SharedWorkspaceLinks Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a link to the list of links in a shared workspace.


SharedWorkspaceLinks.Add Method (Office)

 Copy code hover
[image]

SharedWorkspaceLinks.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a link to the list of links in a shared workspace.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Add(URL, Description, Notes)

expression Required. A variable that represents a SharedWorkspaceLinks object.

Parameters

Name | Required/Optional | Data Type | Description
URL | Required | String | The address of the Web site to which a link is being added.
Description | Optional | String | Description of the link.
Notes | Optional | String | Notes about the link.

Return Value

SharedWorkspaceLink

Example

The following example adds a new link to the links collection of the shared workspace.

VBA Copy code Copy code
    Dim swsLink As Office.SharedWorkspaceLink
    Set swsLink = ActiveWorkbook.SharedWorkspace.Links.Add( _
        "http://msdn.microsoft.com", _
        "Microsoft Developer Network Home Page", _
        "My favorite developer site!")
    MsgBox "New link: " & swsLink.Description, _
        vbInformation + vbOKOnly, _
        "New Link in Shared Workspace"
    Set swsLink = Nothing

See also

Concepts

SharedWorkspaceLinks Object

Other resources

SharedWorkspaceLinks Object Members


SharedWorkspaceMember Object (Office)

 Copy code hover
[image]

SharedWorkspaceMember Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a user who has rights in a shared document workspace site.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Remarks

Use the SharedWorkspaceMember object to manage users who have rights to participate in a shared workspace and to collaborate on the shared documents saved in the workspace site.

The Role specified when the user is added as a member of the workspace (for example, "Reader" or "Contributor") determines that user's rights in the workspace and cannot be accessed or modified later through properties of the SharedWorkspaceMember object.

Use the Item(index) property of the SharedWorkspaceMembers collection to return a specific SharedWorkspaceMember object.

Use the SharedWorkspaceMember object's three distinct name properties to retrieve identifying information about the member.

  • the Name property returns the members display name;

  • the Email property returns the member's e-mail address; and,

  • the DomainName property returns the member's domain and user name in the format domain\user .

Example

The following example displays the number of members in the active document's shared workspace, along with their names, domain user names, and e-mail addresses.

Copy code Copy code
    Dim swsMember As Office.SharedWorkspaceMember
    Dim strMemberInfo As String
    strMemberInfo = "The shared workspace contains " & _
        ActiveWorkbook.SharedWorkspace.Members.Count & " member(s)." & vbCrLf
    If ActiveWorkbook.SharedWorkspace.Members.Count > 0 Then
        For Each swsMember In ActiveWorkbook.SharedWorkspace.Members
            strMemberInfo = strMemberInfo & swsMember.Name & vbCrLf & _
                " - " & swsMember.DomainName & vbCrLf & _
                " - " & swsMember.Email & vbCrLf
        Next
    End If
    MsgBox strMemberInfo, vbInformation + vbOKOnly, _
        "Members in Shared Workspace"
    Set swsMember = Nothing

See also

Concepts

Object Model Reference

Other resources

SharedWorkspaceMember Object Members


SharedWorkspaceMember Members (Office)

 Copy code hover
[image]

SharedWorkspaceMember Members (Office)
Send feedback

Published: July 09, 2012

Represents a user who has rights in a shared document workspace site.

Methods

Name | Description
Delete | Deletes the current SharedWorkspaceMember object.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceMember object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceMember object was created. Read-only.
DomainName | Gets the domain and user name of the specified SharedWorkspaceMember in the format domain\user. Read-only.
Email | Gets the e-mail name of the specified SharedWorkspaceMember in the format user@domain.com. Read-only.
Name | Gets the display name of the shared workspace member. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceMember object. Read-only.


SharedWorkspaceMember Properties (Office)

 Copy code hover
[image]

SharedWorkspaceMember Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceMember object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceMember object was created. Read-only.
DomainName | Gets the domain and user name of the specified SharedWorkspaceMember in the format domain\user. Read-only.
Email | Gets the e-mail name of the specified SharedWorkspaceMember in the format user@domain.com. Read-only.
Name | Gets the display name of the shared workspace member. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceMember object. Read-only.


SharedWorkspaceMember.Application Property (Office)

 Copy code hover
[image]

SharedWorkspaceMember.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SharedWorkspaceMember object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a SharedWorkspaceMember object.

Return Value

Object

See also

Concepts

SharedWorkspaceMember Object

Other resources

SharedWorkspaceMember Object Members


SharedWorkspaceMember.Creator Property (Office)

 Copy code hover
[image]

SharedWorkspaceMember.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SharedWorkspaceMember object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a SharedWorkspaceMember object.

Return Value

Long

Remarks

As an example, if the object was created in Microsoft Word, this property returns 1297307460, which represents the string "MSWD"; in Microsoft Excel, this property returns 1480803660. This value can also be represented by the constant wdCreatorCode in Word, or xlCreatorCode in Excel. The Creator property was primarily designed to be used on the Macintosh, where each application has a four-character creator code. For example, Microsoft Word has the creator code MSWD. For additional information about this property, consult the language reference Help included with Microsoft Office Macintosh Edition.

The Creator property always returns the numeric identifier for the active application, just as the Application property always returns the name of the active applicatin in string form. Use the CreatedBy property of the SharedWorkspaceFile, SharedWorkspaceFolder, SharedWorkspaceLink, and SharedWorkspaceTask objects to return the name of the individual who created those objects. Use document properties to return information about the authors of Office documents.

See also

Concepts

SharedWorkspaceMember Object

Other resources

SharedWorkspaceMember Object Members


SharedWorkspaceMember.DomainName Property (Office)

 Copy code hover
[image]

SharedWorkspaceMember.DomainName Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the domain and user name of the specified SharedWorkspaceMember in the format domain\user. Read-only.

Syntax

expression .DomainName

expression A variable that represents a SharedWorkspaceMember object.

Example

The following example extracts the domain name from the DomainName property of each shared workspace member and lists members who belong to the "MyCompany" domain.

Copy code Copy code
 Dim swsMember As Office.SharedWorkspaceMember
 Dim strDomain As String
 Dim strMemberList As String
 For Each swsMember In ActiveWorkbook.SharedWorkspace.Members
 strDomain = UCase(Left(swsMember.DomainName, _
 InStr(swsMember.DomainName, "\") - 1))
 If strDomain = "MYCOMPANY" Then
 strMemberList = strMemberList & swsMember.Name & vbCrLf
 End If
 Next
 MsgBox strMemberList, vbInformation + vbOKOnly, _
 "Members in the MYCOMPANY Domain"
 Set swsMember = Nothing
Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

See also

Concepts

SharedWorkspaceMember Object

Other resources

SharedWorkspaceMember Object Members


SharedWorkspaceMember.Email Property (Office)

 Copy code hover
[image]

SharedWorkspaceMember.Email Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the e-mail name of the specified SharedWorkspaceMember in the format user@domain.com. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

Email expression.Email

expression An expression that returns a SharedWorkspaceMember object.

Example

The following example extracts the e-mail domain name from the Email property of each shared workspace member and lists members who have e-mail addresses at the "example.com" domain.

Copy code Copy code
Dim swsMember As Office.SharedWorkspaceMember
    Dim strEmailDomain As String
    Dim strMemberList As String
    For Each swsMember In ActiveWorkbook.SharedWorkspace.Members
        strEmailDomain = LCase(Right(swsMember.Email, _
            Len(swsMember.Email) - InStr(swsMember.Email, "@")))
        If strEmailDomain = "example.com" Then
            strMemberList = strMemberList & swsMember.Email & vbCrLf
        End If
    Next
    MsgBox strMemberList, vbInformation + vbOKOnly, _
        "Members with example.com e-mail"
    Set swsMember = Nothing

See also

Concepts

SharedWorkspaceMember Object

Other resources

SharedWorkspaceMember Object Members


SharedWorkspaceMember.Name Property (Office)

 Copy code hover
[image]

SharedWorkspaceMember.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the display name of the shared workspace member. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Name

expression A variable that represents a SharedWorkspaceMember object.

Return Value

String

Example

The following example displays properties of the shared workspace member.

Copy code Copy code
    Dim swsWorkspaceMember As Office.SharedWorkspaceMember
    Dim strSWSInfo As String
    Set swsWorkspaceMember = ActiveWorkbook.SharedWorkspace.Members
    strSWSInfo = swsWorkspaceMember.Name & vbCrLf & _
        " - URL: " & swsWorkspaceMember.URL & vbCrLf
    MsgBox strSWSInfo, vbInformation + vbOKOnly, _
        "Shared Workspace Member Information"
    Set swsWorkspaceMember = Nothing

See also

Concepts

SharedWorkspaceMember Object

Other resources

SharedWorkspaceMember Object Members


SharedWorkspaceMember.Parent Property (Office)

 Copy code hover
[image]

SharedWorkspaceMember.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the SharedWorkspaceMember object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a SharedWorkspaceMember object.

Return Value

Object

See also

Concepts

SharedWorkspaceMember Object

Other resources

SharedWorkspaceMember Object Members


SharedWorkspaceMember Methods (Office)

 Copy code hover
[image]

SharedWorkspaceMember Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes the current SharedWorkspaceMember object.


SharedWorkspaceMember.Delete Method (Office)

 Copy code hover
[image]

SharedWorkspaceMember.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the current SharedWorkspaceMember object.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Delete

expression Required. A variable that represents a SharedWorkspaceMember object.

See also

Concepts

SharedWorkspaceMember Object

Other resources

SharedWorkspaceMember Object Members


SharedWorkspaceMembers Object (Office)

 Copy code hover
[image]

SharedWorkspaceMembers Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of the SharedWorkspaceMember objects in the current shared workspace site.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Example

Use the Members property of the SharedWorkspace object to return a SharedWorkspaceMembers collection.

Copy code Copy code
    Dim swsMembers As Office.SharedWorkspaceMembers
    Set swsMembers = ActiveWorkbook.SharedWorkspace.Members
    MsgBox "There are " & swsMembers.Count & _
        " member(s) in the current shared workspace.", _
        vbInformation + vbOKOnly, _
        "Collection Information"
    Set swsMembers = Nothing

See also

Concepts

Object Model Reference

Other resources

SharedWorkspaceMembers Object Members


SharedWorkspaceMembers Members (Office)

 Copy code hover
[image]

SharedWorkspaceMembers Members (Office)
Send feedback

Published: July 09, 2012

A collection of the SharedWorkspaceMember objects in the current shared workspace site.

Methods

Name | Description
Add | Adds a member to the list of members in a shared workspace site. Returns a SharedWorkspaceMember object.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceMembers object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SharedWorkspaceMembers object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceMembers object was created. Read-only.
Item | Gets a SharedWorkspaceMember object from the Members collection of the shared workspace. Read-only.
ItemCountExceeded | Gets a Boolean value that indicates whether the number of SharedWorkspaceMembers items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceMembers object. Read-only.


SharedWorkspaceMembers Properties (Office)

 Copy code hover
[image]

SharedWorkspaceMembers Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceMembers object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SharedWorkspaceMembers object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceMembers object was created. Read-only.
Item | Gets a SharedWorkspaceMember object from the Members collection of the shared workspace. Read-only.
ItemCountExceeded | Gets a Boolean value that indicates whether the number of SharedWorkspaceMembers items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceMembers object. Read-only.


SharedWorkspaceMembers.Application Property (Office)

 Copy code hover
[image]

SharedWorkspaceMembers.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SharedWorkspaceMembers object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a SharedWorkspaceMembers object.

Return Value

Object

See also

Concepts

SharedWorkspaceMembers Object

Other resources

SharedWorkspaceMembers Object Members


SharedWorkspaceMembers.Count Property (Office)

 Copy code hover
[image]

SharedWorkspaceMembers.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the SharedWorkspaceMembers object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Count

expression A variable that represents a SharedWorkspaceMembers object.

Return Value

Long

See also

Concepts

SharedWorkspaceMembers Object

Other resources

SharedWorkspaceMembers Object Members


SharedWorkspaceMembers.Creator Property (Office)

 Copy code hover
[image]

SharedWorkspaceMembers.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SharedWorkspaceMembers object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a SharedWorkspaceMembers object.

Return Value

Long

Remarks

As an example, if the object was created in Microsoft Word, this property returns 1297307460, which represents the string "MSWD"; in Microsoft Excel, this property returns 1480803660. This value can also be represented by the constant wdCreatorCode in Word, or xlCreatorCode in Excel. The Creator property was primarily designed to be used on the Macintosh, where each application has a four-character creator code. For example, Microsoft Word has the creator code MSWD. For additional information about this property, consult the language reference Help included with Microsoft Office Macintosh Edition.

The Creator property always returns the numeric identifier for the active application, just as the Application property always returns the name of the active applicatin in string form. Use the CreatedBy property of the SharedWorkspaceFile, SharedWorkspaceFolder, SharedWorkspaceLink, and SharedWorkspaceTask objects to return the name of the individual who created those objects. Use document properties to return information about the authors of Office documents.

See also

Concepts

SharedWorkspaceMembers Object

Other resources

SharedWorkspaceMembers Object Members


SharedWorkspaceMembers.Item Property (Office)

 Copy code hover
[image]

SharedWorkspaceMembers.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a SharedWorkspaceMember object from the Members collection of the shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Item(Index)

expression Required. A variable that represents a SharedWorkspaceMembers object. The specified SharedWorkspaceMembers collection.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | Returns the SharedWorkspaceMember at the position specified. The returned SharedWorkspaceMember object does not correspond to the order in which the items are displayed in the Shared Workspace pane, and is not affected by re-sorting the display.

See also

Concepts

SharedWorkspaceMembers Object

Other resources

SharedWorkspaceMembers Object Members


SharedWorkspaceMembers.ItemCountExceeded Property (Office)

 Copy code hover
[image]

SharedWorkspaceMembers.ItemCountExceeded Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value that indicates whether the number of SharedWorkspaceMembers items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ItemCountExceeded

expression A variable that represents a SharedWorkspaceMembers object.

Return Value

Boolean

Remarks

The Shared Workspace task pane can only display 99 shared workspace files and folders, links, members, or tasks. If more than 99 items are added to any of these collections: the corresponding tab of the Shared Workspace task pane stops displaying the list of items and displays a link to the shared workspace site Web page instead; the collection is no longer populated locally and its Count property returns 0 (zero).

Furthermore, once the ItemCountExceeded property returns True for one of the collections listed above, the developer can no longer remedy the situation programmatically by deleting items from the collection to reduce the count below 99, because the collection is no longer populated.

See also

Concepts

SharedWorkspaceMembers Object

Other resources

SharedWorkspaceMembers Object Members


SharedWorkspaceMembers.Parent Property (Office)

 Copy code hover
[image]

SharedWorkspaceMembers.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the SharedWorkspaceMembers object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a SharedWorkspaceMembers object.

Return Value

Object

See also

Concepts

SharedWorkspaceMembers Object

Other resources

SharedWorkspaceMembers Object Members


SharedWorkspaceMembers Methods (Office)

 Copy code hover
[image]

SharedWorkspaceMembers Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a member to the list of members in a shared workspace site. Returns a SharedWorkspaceMember object.


SharedWorkspaceMembers.Add Method (Office)

 Copy code hover
[image]

SharedWorkspaceMembers.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a member to the list of members in a shared workspace site. Returns a SharedWorkspaceMember object.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Add(Email, DomainName, DisplayName, Role)

expression Required. A variable that represents a SharedWorkspaceMembers object.

Parameters

Name | Required/Optional | Data Type | Description
Email | Required | String | The new member's e-mail address in the format user@domain.com. Raises an error if the user is not a valid candidate for membership in the shared workspace site.
DomainName | Required | String | The new member's Windows user name in the format domain\user.
DisplayName | Required | String | The display name to display for the new member.
Role | Optional | String | An optional role that determines the tasks the new member can accomplish in the shared workspace site; for example, "Contributor". An invalid role name raises an error.

Example

The following example adds a new member to the members collection of the shared workspace site in the role of a site contributor.

VBA Copy code Copy code
    Dim swsMember As Office.SharedWorkspaceMember
    Set swsMember = ActiveWorkbook.SharedWorkspace.Members.Add( _
        "user@domain.com", _
        "domain\user", _
        "New User", _
        "Contributor")
    MsgBox "New member: " & swsMember.Name, _
        vbInformation + vbOKOnly, _
        "New Member in Shared Workspace)"
    Set swsMember = Nothing

See also

Concepts

SharedWorkspaceMembers Object

Other resources

SharedWorkspaceMembers Object Members


SharedWorkspaceTask Object (Office)

 Copy code hover
[image]

SharedWorkspaceTask Object (Office)
See also Send feedback

Published: July 09, 2012

The SharedWorkspaceTask object represents a task in a shared document workspace. Member of the SharedWorkspaceTasks collection.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Remarks

Use the SharedWorkspaceTask object to manage tasks assigned to the members who are collaborating on the documents in the shared workspace.

Use the Item(index) property of the SharedWorkspaceTasks collection to return a specific SharedWorkspaceTask object.

Use the Title property to set the text of the task that appears on the Tasks tab of the Shared Workspace task pane and on the shared workspace Web page. Use the Description property to supply additional information about the task.

Assign the task to a member of the workspace using the AssignedTo property and the member's domain user name. Specify a due date for the task using the DueDate property.

Use the enumerations for task Priority and Status to indicate the relative importance of the task and to update the task's status.

Use the Save method to upload changes to the server after you modify properties of the SharedWorkspaceTask object.

Use the CreatedBy, CreatedDate, ModifiedBy, and ModifiedDate properties to return information about the history of each task.

Example

The following example returns the number of tasks in the shared workspace and information about each task.

Copy code Copy code
    Dim swsTask As Office.SharedWorkspaceTask
    Dim strTaskInfo As String
    strTaskInfo = "The shared workspace contains " & _
    ActiveWorkbook.SharedWorkspace.Tasks.Count & " Task(s)." & vbCrLf
    For Each swsTask In ActiveWorkbook.SharedWorkspace.Tasks
        strTaskInfo = strTaskInfo & swsTask.Title & vbCrLf & _
            " - Description: " & swsTask.Description & vbCrLf & _
            " - Assigned to: " & swsTask.AssignedTo & vbCrLf & _
            " - Due date: " & swsTask.DueDate & vbCrLf & _
            " - Priority: " & swsTask.Priority & vbCrLf & _
            " - Status: " & swsTask.Status & vbCrLf
    Next
    MsgBox strTaskInfo, vbInformation + vbOKOnly, _
        "Tasks in Shared Workspace"
    Set swsTask = Nothing

See also

Concepts

Object Model Reference

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask Members (Office)

 Copy code hover
[image]

SharedWorkspaceTask Members (Office)
Send feedback

Published: July 09, 2012

The SharedWorkspaceTask object represents a task in a shared document workspace. Member of the SharedWorkspaceTasks collection.

Methods

Name | Description
Delete | Deletes the current SharedWorkspaceTask object.
Save | Uploads changes made programmatically to a shared server.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceTask object (you can use this property with an Automation object to return that object's container application). Read-only.
AssignedTo | Gets or sets a value containing the name of the one assigned to the task represented by the SharedWorkspaceTask object. Read/write.
CreatedBy | Gets the display name of the member who created the shared workspace object. Read-only.
CreatedDate | Gets the date and time when the shared workspace object was created. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceTask object was created. Read-only.
Description | Gets or sets a descriptive String value for the specified SharedWorkspaceLink or SharedWorkspaceTask object. Read/write.
DueDate | Gets or sets the optional due date and time of a SharedWorkspaceTask object. Read/write.
ModifiedBy | Gets the name of the user who last modified the object. Read-only.
ModifiedDate | Gets the date and time when the SharedWorkspaceTask object was last modified. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceTask object. Read-only.
Priority | Gets or sets the status of the specified shared workspace task. Read/write.
Status | Gets or sets the status of the specified shared workspace task. Read/write .
Title | Sets or gets the title of a SharedWorkspaceTask object. Read/write.


SharedWorkspaceTask Properties (Office)

 Copy code hover
[image]

SharedWorkspaceTask Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceTask object (you can use this property with an Automation object to return that object's container application). Read-only.
AssignedTo | Gets or sets a value containing the name of the one assigned to the task represented by the SharedWorkspaceTask object. Read/write.
CreatedBy | Gets the display name of the member who created the shared workspace object. Read-only.
CreatedDate | Gets the date and time when the shared workspace object was created. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceTask object was created. Read-only.
Description | Gets or sets a descriptive String value for the specified SharedWorkspaceLink or SharedWorkspaceTask object. Read/write.
DueDate | Gets or sets the optional due date and time of a SharedWorkspaceTask object. Read/write.
ModifiedBy | Gets the name of the user who last modified the object. Read-only.
ModifiedDate | Gets the date and time when the SharedWorkspaceTask object was last modified. Read-only.
Parent | Gets the Parent object for the SharedWorkspaceTask object. Read-only.
Priority | Gets or sets the status of the specified shared workspace task. Read/write.
Status | Gets or sets the status of the specified shared workspace task. Read/write .
Title | Sets or gets the title of a SharedWorkspaceTask object. Read/write.


SharedWorkspaceTask.Application Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SharedWorkspaceTask object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a SharedWorkspaceTask object.

Return Value

Object

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.AssignedTo Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.AssignedTo Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value containing the name of the one assigned to the task represented by the SharedWorkspaceTask object. Read/write.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .AssignedTo

expression An expression that returns a SharedWorkspaceTask object.

Return Value

String

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.CreatedBy Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.CreatedBy Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the display name of the member who created the shared workspace object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .CreatedBy

expression A variable that represents a SharedWorkspaceTask object.

Return Value

String

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.CreatedDate Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.CreatedDate Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the date and time when the shared workspace object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .CreatedDate

expression A variable that represents a SharedWorkspaceTask object.

Return Value

Variant

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.Creator Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SharedWorkspaceTask object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a SharedWorkspaceTask object.

Return Value

Long

Remarks

As an example, if the object was created in Microsoft Word, this property returns 1297307460, which represents the string "MSWD"; in Microsoft Excel, this property returns 1480803660. This value can also be represented by the constant wdCreatorCode in Word, or xlCreatorCode in Excel. The Creator property was primarily designed to be used on the Macintosh, where each application has a four-character creator code. For example, Microsoft Word has the creator code MSWD. For additional information about this property, consult the language reference Help included with Microsoft Office Macintosh Edition.

The Creator property always returns the numeric identifier for the active application, just as the Application property always returns the name of the active applicatin in string form. Use the CreatedBy property of the SharedWorkspaceTask object to return the name of the individual who created the object. Use document properties to return information about the authors of Office documents.

Example

This example displays a message about the creator of "myObject" variable.

Copy code Copy code
Set myObject = ActiveDocument
If myObject.Creator = wdCreatorCode Then
    MsgBox "This is a Microsoft Word object"
Else
    MsgBox "This is not a Microsoft Word object"
End If

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.Description Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.Description Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a descriptive String value for the specified SharedWorkspaceLink or SharedWorkspaceTask object. Read/write.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Description

expression Required. A variable that represents a SharedWorkspaceTask object.

Remarks

The Description property is optional when a new shared workspace link or task is created, and may be empty.

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.DueDate Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.DueDate Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the optional due date and time of a SharedWorkspaceTask object. Read/write.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression.DueDate()

expression An expression that returns a SharedWorkspaceTask object.

Example

The following example sets the DueDate of all tasks in a shared workspace to 12:00 noon on December 31, 2005 and uploads these changes to the server using the Save method.

VBA Copy code Copy code
Dim swsTask As Office.SharedWorkspaceTask
    Const dtmNewDueDate As Date = #12/31/2005 12:00:00 PM#
    For Each swsTask In ActiveWorkbook.SharedWorkspace.Tasks
        swsTask.DueDate = dtmNewDueDate
        swsTask.Save
    Next
    Set swsTask = Nothing

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.ModifiedBy Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.ModifiedBy Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the user who last modified the object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ModifiedBy

expression A variable that represents a SharedWorkspaceTask object.

Return Value

String

Remarks

For shared workspace objects, the ModifiedBy property returns the display name stored in the Name property of the SharedWorkspaceMember object. The SharedWorkspaceMember object does not have a ModifiedBy property.

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.ModifiedDate Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.ModifiedDate Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the date and time when the SharedWorkspaceTask object was last modified. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ModifiedDate

expression A variable that represents a SharedWorkspaceTask object.

Return Value

Variant

Example

The following example returns a list of shared workspace files whose date and time last modified is earlier than today.

VBA Copy code Copy code
Dim swsFile As Office.SharedWorkspaceFile
    Dim dtmMidnight As Date
    Dim dtmFileDate As Date
    Dim strOlderFiles As String
    dtmMidnight = CDate(FormatDateTime(Now, vbShortDate) & " 12:00:00 am")
    For Each swsFile In ActiveWorkbook.SharedWorkspace.Files
        dtmFileDate = swsFile.ModifiedDate
        If dtmFileDate < dtmMidnight Then
            strOlderFiles = strOlderFiles & swsFile.URL & vbCrLf
        End If
    Next
    MsgBox "Files not modified today: " & vbCrLf & strOlderFiles, _
        vbInformation + vbOKOnly, "Older Files"
    Set swsFile = Nothing

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.Parent Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the SharedWorkspaceTask object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a SharedWorkspaceTask object.

Return Value

Object

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.Priority Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.Priority Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the status of the specified shared workspace task. Read/write.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Priority

expression Required. A variable that represents a SharedWorkspaceTask object.

Remarks

The shared workspace task schema on the server can be customized. Customization of the schema may affect the task priority enumeration when the Add or Save method is called. Priority property values are mapped as follows:

  • Downloaded value 1 is mapped to msoSharedWorkspaceTaskPriority 1 (msoSharedWorkspaceTaskPriorityHigh). Downloaded values 2 through N-1 are mapped to msoSharedWorkspaceTaskPriority 2 (msoSharedWorkspaceTaskPriorityNormal). Downloaded value N is mapped to msoSharedWorkspaceTaskPriority 3 (msoSharedWorkspaceTaskPriorityLow).

  • Uploaded enumeration values 1 through 3 are mapped to schema values 1 through 3. If a user-specified value does not map to any value defined in the schema, the user-specified value is silently ignored and the Status property is not updated on the server.

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.Status Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.Status Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the status of the specified shared workspace task. Read/write .

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Status

expression Required. A variable that represents a SharedWorkspaceTask object.

Remarks

The shared workspace task schema on the server can be customized. Customization of the schema may affect the task status enumeration when the Add or Save method is called. Status property values are mapped as follows:

  • Downloaded values 1 through 5 are mapped to msoSharedWorkspaceTaskStatus enumeration values 1 through 5. Schema values beyond 5 are mapped to enumeration value 1 (msoSharedWorkspaceTaskStatusInProgress).

  • Uploaded enumeration values 1 through 5 are mapped to schema values 1 through 5. If a user-specified value does not map to any value defined in the schema, the user-specified value is silently ignored and the Status property is not updated on the server.

Example

The following example displays a list of all tasks in the current shared workspace whose status is not set to Complete.

VBA Copy code Copy code
    Dim swsTask As Office.SharedWorkspaceTask
    Dim strTaskStatus As String
    For Each swsTask In ActiveWorkbook.SharedWorkspace.Tasks
        If swsTask.Status <> msoSharedWorkspaceTaskStatusCompleted Then
            strTaskStatus = strTaskStatus & swsTask.Title & vbCrLf
        End If
    Next
    MsgBox "The following tasks have not been completed:" & vbCrLf & _
        strTaskStatus, vbInformation + vbOKOnly, "Incomplete Tasks"
    Set swsTask = Nothing

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.Title Property (Office)

 Copy code hover
[image]

SharedWorkspaceTask.Title Property (Office)
See also Send feedback

Published: July 09, 2012

Sets or gets the title of a SharedWorkspaceTask object. Read/write.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Title

expression A variable that represents a SharedWorkspaceTask object.

Return Value

String

Remarks

The Title property is the single required property of a shared workspace task. Use the optional Description property to provide or return additional information about the task.

Example

The following example displays a list of the titles of all tasks in the current shared workspace.

Copy code Copy code
 Dim swsTask As Office.SharedWorkspaceTask
    Dim strTasks As String
    For Each swsTask In ActiveWorkbook.SharedWorkspace.Tasks
        strTasks = strTasks & swsTask.Title & vbCrLf
    Next
    MsgBox strTasks, vbInformation + vbOKOnly, _
        "Tasks in Shared Workspace"
    Set swsTask = Nothing

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask Methods (Office)

 Copy code hover
[image]

SharedWorkspaceTask Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes the current SharedWorkspaceTask object.
Save | Uploads changes made programmatically to a shared server.


SharedWorkspaceTask.Delete Method (Office)

 Copy code hover
[image]

SharedWorkspaceTask.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the current SharedWorkspaceTask object.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Delete

expression Required. A variable that represents a SharedWorkspaceTask object.

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTask.Save Method (Office)

 Copy code hover
[image]

SharedWorkspaceTask.Save Method (Office)
See also Send feedback

Published: July 09, 2012

Uploads changes made programmatically to a shared server.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Save

expression A variable that represents a SharedWorkspaceTask object.

Parameters

Name | Required/Optional | Data Type | Description
bstrQueryName | Required | String | Name of the query used to change the property of the shared workspcae link.

Remarks

Use the Save method to upload changes to the server after changing the properties of a shared workspace task.

See also

Concepts

SharedWorkspaceTask Object

Other resources

SharedWorkspaceTask Object Members


SharedWorkspaceTasks Object (Office)

 Copy code hover
[image]

SharedWorkspaceTasks Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of the SharedWorkspaceTask objects in the current shared workspace site.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Example

Use the Tasks property of the SharedWorkspace object to return a SharedWorkspaceTasks collection.

VBA Copy code Copy code
    Dim swsTasks As Office.SharedWorkspaceTasks
    Set swsTasks = ActiveWorkbook.SharedWorkspace.Tasks
    MsgBox "There are " & swsTasks.Count & _
        " task(s) in the current shared workspace.", _
        vbInformation + vbOKOnly, _
        "Collection Information"
    Set swsTasks = Nothing

See also

Concepts

Object Model Reference

Other resources

SharedWorkspaceTasks Object Members


SharedWorkspaceTasks Members (Office)

 Copy code hover
[image]

SharedWorkspaceTasks Members (Office)
Send feedback

Published: July 09, 2012

A collection of the SharedWorkspaceTask objects in the current shared workspace site.

Methods

Name | Description
Add | Adds a task to the list of tasks in a shared workspace. Returns a SharedWorkspaceTask object.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceTasks object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SharedWorkspaceTasks object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceTasks object was created. Read-only.
Item | Gets a SharedWorkspaceTask object from the Tasks collection of the shared workspace. Read-only.
ItemCountExceeded | Gets a Boolean value that indicates whether the number of SharedWorkspaceTasks items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.
Parent | Getss the Parent object for the SharedWorkspaceTasks object. Read-only.


SharedWorkspaceTasks Properties (Office)

 Copy code hover
[image]

SharedWorkspaceTasks Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SharedWorkspaceTasks object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the SharedWorkspaceTasks object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SharedWorkspaceTasks object was created. Read-only.
Item | Gets a SharedWorkspaceTask object from the Tasks collection of the shared workspace. Read-only.
ItemCountExceeded | Gets a Boolean value that indicates whether the number of SharedWorkspaceTasks items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.
Parent | Getss the Parent object for the SharedWorkspaceTasks object. Read-only.


SharedWorkspaceTasks.Application Property (Office)

 Copy code hover
[image]

SharedWorkspaceTasks.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SharedWorkspaceTasks object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a SharedWorkspaceTasks object.

Return Value

Object

See also

Concepts

SharedWorkspaceTasks Object

Other resources

SharedWorkspaceTasks Object Members


SharedWorkspaceTasks.Count Property (Office)

 Copy code hover
[image]

SharedWorkspaceTasks.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the SharedWorkspaceTasks object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Count

expression A variable that represents a SharedWorkspaceTasks object.

Return Value

Long

See also

Concepts

SharedWorkspaceTasks Object

Other resources

SharedWorkspaceTasks Object Members


SharedWorkspaceTasks.Creator Property (Office)

 Copy code hover
[image]

SharedWorkspaceTasks.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SharedWorkspaceTasks object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a SharedWorkspaceTasks object.

Return Value

Long

Remarks

As an example, if the object was created in Microsoft Word, this property returns 1297307460, which represents the string "MSWD"; in Microsoft Excel, this property returns 1480803660. This value can also be represented by the constant wdCreatorCode in Word, or xlCreatorCode in Excel. The Creator property was primarily designed to be used on the Macintosh, where each application has a four-character creator code. For example, Microsoft Word has the creator code MSWD. For additional information about this property, consult the language reference Help included with Microsoft Office Macintosh Edition.

The Creator property always returns the numeric identifier for the active application, just as the Application property always returns the name of the active applicatin in string form. Use the CreatedBy property of theSharedWorkspaceTask object to return the name of the individual who created the objects. Use document properties to return information about the authors of Office documents.

Example

This example displays a message about the creator of "myObject" variable.

Copy code Copy code
Set myObject = ActiveDocument
If myObject.Creator = wdCreatorCode Then
    MsgBox "This is a Microsoft Word object"
Else
    MsgBox "This is not a Microsoft Word object"
End If

See also

Concepts

SharedWorkspaceTasks Object

Other resources

SharedWorkspaceTasks Object Members


SharedWorkspaceTasks.Item Property (Office)

 Copy code hover
[image]

SharedWorkspaceTasks.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a SharedWorkspaceTask object from the Tasks collection of the shared workspace. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Item(Index)

expression Required. A variable that represents a SharedWorkspaceTasks object. The specified SharedWorkspaceTasks collection.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | Returns the SharedWorkspaceTask at the position specified. The returned SharedWorkspaceTask object does not correspond to the order in which the items are displayed in the Shared Workspace pane, and is not affected by re-sorting the display.

See also

Concepts

SharedWorkspaceTasks Object

Other resources

SharedWorkspaceTasks Object Members


SharedWorkspaceTasks.ItemCountExceeded Property (Office)

 Copy code hover
[image]

SharedWorkspaceTasks.ItemCountExceeded Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value that indicates whether the number of SharedWorkspaceTasks items in the collection has exceeded the 99 that can be displayed in the Shared Workspace task pane. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ItemCountExceeded

expression A variable that represents a SharedWorkspaceTasks object.

Return Value

Boolean

Remarks

The Shared Workspace task pane can only display 99 shared workspace files and folders, links, members, or tasks. If more than 99 items are added to any of these collections: the corresponding tab of the Shared Workspace task pane stops displaying the list of items and displays a link to the shared workspace site Web page instead; the collection is no longer populated locally and its Count property returns 0 (zero).

Furthermore, once the ItemCountExceeded property returns True for one of the collections listed above, the developer can no longer remedy the situation programmatically by deleting items from the collection to reduce the count below 99, because the collection is no longer populated.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

See also

Concepts

SharedWorkspaceTasks Object

Other resources

SharedWorkspaceTasks Object Members


SharedWorkspaceTasks.Parent Property (Office)

 Copy code hover
[image]

SharedWorkspaceTasks.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Getss the Parent object for the SharedWorkspaceTasks object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a SharedWorkspaceTasks object.

Return Value

Object

See also

Concepts

SharedWorkspaceTasks Object

Other resources

SharedWorkspaceTasks Object Members


SharedWorkspaceTasks Methods (Office)

 Copy code hover
[image]

SharedWorkspaceTasks Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a task to the list of tasks in a shared workspace. Returns a SharedWorkspaceTask object.


SharedWorkspaceTasks.Add Method (Office)

 Copy code hover
[image]

SharedWorkspaceTasks.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a task to the list of tasks in a shared workspace. Returns a SharedWorkspaceTask object.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Add(Title, Status, Priority, Assignee, Description, Due Date)

expression Required. A variable that represents a SharedWorkspaceTasks object.

Parameters

Name | Required/Optional | Data Type | Description
Title | Required | String | The title of the new task.
Status | Optional | msoSharedWorkspaceTask | The status of the new task. Default is msoSharedWorkspaceTaskNotStarted.
Priority | Optional | msoSharedWorkspaceTask | The priority of the new task. Default is msoSharedWorkspaceTaskNormal.
Assignee | Optional | SharedWorkspaceMember | The member to whom the new task is assigned.
Description | Optional | String | The description of the new task.
DueDate | Optional | Date | The due date of the new task.

Remarks

The schema that defines shared workspace tasks and their properties for a SharePoint site can be modified on the server in such a way that the Add method of the SharedWorkspaceTasks collection may raise an error, or may disregard the values of certain arguments. In particular, the task status and priority enumerations can be customized. Some examples of the problems that can result are mentioned below:

  • If a Status argument is supplied, and the status field has been removed from the customized tasks schema, the argument will be ignored and no error will be raised.

  • If a Status value is supplied that lies outside the status values recognized by the customized tasks schema, the argument will be ignored, the default value will be used, and no error will be raised.

  • If a new required field has been added to the customized tasks schema, then the Add method will fail with an error, and it will no longer be possible to use the Add method to add new tasks.

Example

The following example adds a new task to the tasks collection of the shared workspace, specifies a due date, and assigns the task to the first member of the shared workspace.

VBA Copy code Copy code
   Dim swsTask As Office.SharedWorkspaceTask
    Dim swsMember As Office.SharedWorkspaceMember
    Set swsMember = ActiveWorkbook.SharedWorkspace.Members(1)
    Set swsTask = ActiveWorkbook.SharedWorkspace.Tasks.Add( _
        "Complete document by year-end", _
        msoSharedWorkspaceTaskStatusNotStarted, _
        msoSharedWorkspaceTaskPriorityNormal, _
        swsMember, _
        "My first shared workspace task", #12/31/2005#)
    MsgBox "New task: " & swsTask.Title, _
        vbInformation + vbOKOnly, _
        "New Task in Shared Workspace"
    Set swsMember = Nothing
    Set swsTask = Nothing

See also

Concepts

SharedWorkspaceTasks Object

Other resources

SharedWorkspaceTasks Object Members


Signature Object (Office)

 Copy code hover
[image]

Signature Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a digital signature attached to a document. Signature objects are contained in the SignatureSet collection of the Document object.

Remarks

You can add a Signature object to a SignatureSet collection using the Add method and you can return an existing member using the Item method. To remove a Signature from a SignatureSet collection, use the Delete method of the Signature object.

Example

The following example prompts the user to select a digital signature with which to sign the active document in Microsoft Word. To use this example, open a document in Word and pass this function the name of a certificate issuer and the name of a certificate signer that match the Issued By and Issued To fields of a digital certificate in the Digital Certificates dialog box. This example will test to make sure that the digital signature that the user selects meets certain criteria, such as not having expired, before the new signature is committed to the disk.

Copy code Copy code
Function AddSignature(ByVal strIssuer As String, _
 strSigner As String) As Boolean

 On Error GoTo Error_Handler

 Dim sig As Signature

 'Display the dialog box that lets the
 'user select a digital signature.
 'If the user selects a signature, then
 'it is added to the Signatures
 'collection. If the user does not, then
 'an error is returned.
 Set sig = ActiveDocument.Signatures.Add

 'Test several properties before commiting the Signature object to disk.
 If sig.Issuer = strIssuer And _
 sig.Signer = strSigner And _
 sig.IsCertificateExpired = False And _
 sig.IsCertificateRevoked = False And _
 sig.IsValid = True Then

 MsgBox "Signed"
 AddSignature = True
 'Otherwise, remove the Signature object from the SignatureSet collection.
 Else
 sig.Delete
 MsgBox "Not signed"
 AddSignature = False
 End If

 'Commit all signatures in the SignatureSet collection to the disk.
 ActiveDocument.Signatures.Commit

 Exit Function
Error_Handler:
 AddSignature = False
 MsgBox "Action canceled."
End Function

See also

Concepts

Object Model Reference

Other resources

Signature Object Members


Signature Members (Office)

 Copy code hover
[image]

Signature Members (Office)
Send feedback

Published: July 09, 2012

Represents a digital signature attached to a document. Signature objects are contained in the SignatureSet collection of the Document object.

Methods

Name | Description
Delete | Deletes the Signature object from the collection.
ShowDetails | Displays details related to a signature packet.
Sign | Creates a signature packet.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the Signature object (you can use this property with an Automation object to return that object's container application). Read-only.
CanSetup | Gets a Boolean value indicating whether the user can set properties of the Signature object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the Signature object was created. Read-only.
Details | Gets information about a signature. Read-only.
IsSignatureLine | Gets a value indicating whether this is a signature line. Read-only.
IsSigned | Gets a Boolean value indicating whether the document was signed successfully. Read-only.
Parent | Gets the Parent object for the Signature object. Read-only.
Setup | Gets a SignatureSetup object that provides access to various properties of a signature packet. Read-only.
SignatureLineShape | Gets the Shape object associated with a Signature object that is a signature line. Read-only.
SortHint | Gets a value representing the sort order of the signatures in a packet with multiple signatures. Read-only.


Signature Properties (Office)

 Copy code hover
[image]

Signature Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the Signature object (you can use this property with an Automation object to return that object's container application). Read-only.
CanSetup | Gets a Boolean value indicating whether the user can set properties of the Signature object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the Signature object was created. Read-only.
Details | Gets information about a signature. Read-only.
IsSignatureLine | Gets a value indicating whether this is a signature line. Read-only.
IsSigned | Gets a Boolean value indicating whether the document was signed successfully. Read-only.
Parent | Gets the Parent object for the Signature object. Read-only.
Setup | Gets a SignatureSetup object that provides access to various properties of a signature packet. Read-only.
SignatureLineShape | Gets the Shape object associated with a Signature object that is a signature line. Read-only.
SortHint | Gets a value representing the sort order of the signatures in a packet with multiple signatures. Read-only.


Signature.Application Property (Office)

 Copy code hover
[image]

Signature.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the Signature object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a Signature object.

Return Value

Object

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature.CanSetup Property (Office)

 Copy code hover
[image]

Signature.CanSetup Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value indicating whether the user can set properties of the Signature object. Read-only.

Syntax

expression .CanSetup

expression An expression that returns a Signature object.

Return Value

Boolean

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature.Creator Property (Office)

 Copy code hover
[image]

Signature.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the Signature object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a Signature object.

Return Value

Long

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature.Details Property (Office)

 Copy code hover
[image]

Signature.Details Property (Office)
See also Send feedback

Published: July 09, 2012

Gets information about a signature. Read-only.

Syntax

expression .Details

expression An expression that returns a Signature object.

Return Value

SignatureInfo

Remarks

Among the information that can be read is whether the certificate associated with the signature has expired, whether the signature is valid, and whether the signature is read-only.

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature.IsSignatureLine Property (Office)

 Copy code hover
[image]

Signature.IsSignatureLine Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value indicating whether this is a signature line. Read-only.

Syntax

expression .IsSignatureLine

expression An expression that returns a Signature object.

Return Value

Boolean

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature.IsSigned Property (Office)

 Copy code hover
[image]

Signature.IsSigned Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value indicating whether the document was signed successfully. Read-only.

Syntax

expression .IsSigned

expression An expression that returns a Signature object.

Return Value

Boolean

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature.Parent Property (Office)

 Copy code hover
[image]

Signature.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the Signature object. Read-only.

Syntax

expression .Parent

expression A variable that represents a Signature object.

Return Value

Object

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature.Setup Property (Office)

 Copy code hover
[image]

Signature.Setup Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a SignatureSetup object that provides access to various properties of a signature packet. Read-only.

Syntax

expression .Setup

expression An expression that returns a Signature object.

Return Value

SignatureSetup

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature.SignatureLineShape Property (Office)

 Copy code hover
[image]

Signature.SignatureLineShape Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Shape object associated with a Signature object that is a signature line. Read-only.

Syntax

expression .SignatureLineShape

expression An expression that returns a Signature object.

Return Value

Object

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature.SortHint Property (Office)

 Copy code hover
[image]

Signature.SortHint Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value representing the sort order of the signatures in a packet with multiple signatures. Read-only.

Syntax

expression .SortHint

expression An expression that returns a Signature object.

Return Value

Long

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature Methods (Office)

 Copy code hover
[image]

Signature Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Delete | Deletes the Signature object from the collection.
ShowDetails | Displays details related to a signature packet.
Sign | Creates a signature packet.


Signature.Delete Method (Office)

 Copy code hover
[image]

Signature.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the Signature object from the collection.

Syntax

expression .Delete

expression Required. A variable that represents a Signature object.

Remarks

For the Scripts collection, using the Delete method removes all scripts from the specified Microsoft Word document, Microsoft Excel worksheet, or Microsoft PowerPoint slide. A script anchor is represented by a shape in the host application. Therefore, the Shape object associated with each script anchor of type msoScriptAnchor is deleted from the Shapes collection in Excel and PowerPoint and from the InlineShapes and Shapes collections in Word.

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature.ShowDetails Method (Office)

 Copy code hover
[image]

Signature.ShowDetails Method (Office)
See also Send feedback

Published: July 09, 2012

Displays details related to a signature packet.

Syntax

expression .ShowDetails

expression An expression that returns a Signature object.

Example

The following example calls the ShowDetails method to show details of the Signature object.

VBA Copy code Copy code
Sub getSignatureDetails(ByVal objSignature As Signature)
If objSignature.IsSigned then
 Msgbox(The document has been signed with the following details: " & objSignature.ShowDetails)
Else
 Msgbox("The document has not been signed.")
End If
End Sub

See also

Concepts

Signature Object

Other resources

Signature Object Members


Signature.Sign Method (Office)

 Copy code hover
[image]

Signature.Sign Method (Office)
See also Send feedback

Published: July 09, 2012

Creates a signature packet.

Syntax

expression .Sign(varSigImg, varDelSuggSigner, varDelSuggSignerLine2, varDelSuggSignerEmail)

expression An expression that returns a Signature object.

Parameters

Name | Required/Optional | Data Type | Description
varSigImg | Optional | Variant | The signature line graphic image.
varDelSuggSigner | Optional | Variant | The suggested signer.
varDelSuggSignerLine2 | Optional | Variant | The additional signature line.
varDelSuggSignerEmail | Optional | Variant | The e-mail address of the suggested signer.

Remarks

When the Sign method is called, Microsoft Office creates a manifest and calls the signature provider to create a hash for each stream in the document. Office then bundles up the results into an unsigned XMLDSIG template and calls to the provider to modify the XMLDSIG (if necessary) and then sign it. The resulting signed signature is then handed back to Office to be stored.

Example

In the following example, the variables for the signature image, signer, signer's title, and signer's e-mail address are set and then the Sign method is called to create and sign a signature packet.

VBA Copy code Copy code
Set objSignature = New Signature
varSigline = CType(AxHost2.GetIPictureDispFromPicture(img),IPictureDisp)
varSuggestedSigner = "Nancy Davolio"
varSignatureTitle = "Sales Represenative"
varSignerEmail = "ndavolio@northwindtraders.com"
objSignature.Sign(varSigline, varSuggestedSigner, varSignatureTitle, varSignerEmail)

See also

Concepts

Signature Object

Other resources

Signature Object Members


SignatureInfo Object (Office)

 Copy code hover
[image]

SignatureInfo Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the information used to create a digital or in-document signature.

Example

The following example uses the GetCertificationDetails method of the SignatureInfo object to get the expiration date of the digital certificate.

VBA Copy code Copy code
Sub GetCertDetails()
Dim objSignatureInfo As SignatureInfo
Dim varDetail As Variant

strDetail = objSignatureInfo.GetCertificationDetail(certdetExpirationDate)

End Sub

See also

Concepts

Object Model Reference

Other resources

SignatureInfo Object Members


SignatureInfo Members (Office)

 Copy code hover
[image]

SignatureInfo Members (Office)
Send feedback

Published: July 09, 2012

Represents the information used to create a digital or in-document signature.

Methods

Name | Description
GetCertificateDetail | Displays a specified detail related to a digital certificate.
GetSignatureDetail | Displays a specified detail related to a signature.
SelectCertificateDetailByThumbprint | Displays a dialog box containing information about a digital certificate following vertification of the user from a thumbprint.
SelectSignatureCertificate | Displays a dialog box that allows users to select which signature certificate to use for signing a document.
ShowSignatureCertificate | Displays the selected or default digital certificate.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SignatureInfo object. Read-only.
CertificateVerificationResults | Gets the results from the verification of a digital certificate. Read-only.
ContentVerificationResults | Gets a value representing the results of the verification of the hashed contents of a signed document. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SignatureInfo object was created. Read-only.
IsCertificateExpired | Gets a Boolean value indicating whether the digital certificate is expired. Read-only.
IsCertificateRevoked | Gets a Boolean value indicating whether the digital certificate is revoked. Read-only.
IsCertificateUntrusted | Gets a Boolean value indicating whether the digital certificate used to digitally sign a document comes from a trusted source. Read-only.
IsValid | Gets a Boolean value indicating whether the signature was successfully validated following signature verification. Read-only.
ReadOnly | Gets a Boolean value indicating whether the SignatureInfo object is read-only. Read-only.
SignatureComment | Gets or sets a value containing comments included in a signature packet. Read/write.
SignatureImage | Gets or sets the value of the image used to sign the document. Read/write.
SignatureProvider | Gets a value identifying an installed signature provider add-in. Read-only.
SignatureText | Gets or sets the value of the signature text used to sign this document. Read/write.


SignatureInfo Properties (Office)

 Copy code hover
[image]

SignatureInfo Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SignatureInfo object. Read-only.
CertificateVerificationResults | Gets the results from the verification of a digital certificate. Read-only.
ContentVerificationResults | Gets a value representing the results of the verification of the hashed contents of a signed document. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SignatureInfo object was created. Read-only.
IsCertificateExpired | Gets a Boolean value indicating whether the digital certificate is expired. Read-only.
IsCertificateRevoked | Gets a Boolean value indicating whether the digital certificate is revoked. Read-only.
IsCertificateUntrusted | Gets a Boolean value indicating whether the digital certificate used to digitally sign a document comes from a trusted source. Read-only.
IsValid | Gets a Boolean value indicating whether the signature was successfully validated following signature verification. Read-only.
ReadOnly | Gets a Boolean value indicating whether the SignatureInfo object is read-only. Read-only.
SignatureComment | Gets or sets a value containing comments included in a signature packet. Read/write.
SignatureImage | Gets or sets the value of the image used to sign the document. Read/write.
SignatureProvider | Gets a value identifying an installed signature provider add-in. Read-only.
SignatureText | Gets or sets the value of the signature text used to sign this document. Read/write.


SignatureInfo.Application Property (Office)

 Copy code hover
[image]

SignatureInfo.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SignatureInfo object. Read-only.

Syntax

expression .Application

expression An expression that returns a SignatureInfo object.

Return Value

Object

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.CertificateVerificationResults Property (Office)

 Copy code hover
[image]

SignatureInfo.CertificateVerificationResults Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the results from the verification of a digital certificate. Read-only.

Syntax

expression .CertificateVerificationResults

expression An expression that returns a SignatureInfo object.

Return Value

CertificateVerificationResults

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.ContentVerificationResults Property (Office)

 Copy code hover
[image]

SignatureInfo.ContentVerificationResults Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value representing the results of the verification of the hashed contents of a signed document. Read-only.

Syntax

expression .ContentVerificationResults

expression An expression that returns a SignatureInfo object.

Return Value

ContentVerificationResults

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.Creator Property (Office)

 Copy code hover
[image]

SignatureInfo.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SignatureInfo object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a SignatureInfo object.

Return Value

Long

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.IsCertificateExpired Property (Office)

 Copy code hover
[image]

SignatureInfo.IsCertificateExpired Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value indicating whether the digital certificate is expired. Read-only.

Syntax

expression .IsCertificateExpired

expression An expression that returns a SignatureInfo object.

Return Value

Boolean

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.IsCertificateRevoked Property (Office)

 Copy code hover
[image]

SignatureInfo.IsCertificateRevoked Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value indicating whether the digital certificate is revoked. Read-only.

Syntax

expression .IsCertificateRevoked

expression An expression that returns a SignatureInfo object.

Return Value

Boolean

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.IsCertificateUntrusted Property (Office)

 Copy code hover
[image]

SignatureInfo.IsCertificateUntrusted Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value indicating whether the digital certificate used to digitally sign a document comes from a trusted source. Read-only.

Syntax

expression .IsCertificateUntrusted

expression An expression that returns a SignatureInfo object.

Return Value

Boolean

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.IsValid Property (Office)

 Copy code hover
[image]

SignatureInfo.IsValid Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value indicating whether the signature was successfully validated following signature verification. Read-only.

Syntax

expression .IsValid

expression An expression that returns a SignatureInfo object.

Return Value

Boolean

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.ReadOnly Property (Office)

 Copy code hover
[image]

SignatureInfo.ReadOnly Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value indicating whether the SignatureInfo object is read-only. Read-only.

Syntax

expression .ReadOnly

expression An expression that returns a SignatureInfo object.

Return Value

Boolean

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.SignatureComment Property (Office)

 Copy code hover
[image]

SignatureInfo.SignatureComment Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value containing comments included in a signature packet. Read/write.

Syntax

expression .SignatureComment

expression An expression that returns a SignatureInfo object.

Return Value

String

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.SignatureImage Property (Office)

 Copy code hover
[image]

SignatureInfo.SignatureImage Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the value of the image used to sign the document. Read/write.

Syntax

expression .SignatureImage

expression An expression that returns a SignatureInfo object.

Return Value

IPictDisp

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.SignatureProvider Property (Office)

 Copy code hover
[image]

SignatureInfo.SignatureProvider Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value identifying an installed signature provider add-in. Read-only.

Syntax

expression .SignatureProvider

expression An expression that returns a SignatureInfo object.

Return Value

String

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.SignatureText Property (Office)

 Copy code hover
[image]

SignatureInfo.SignatureText Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the value of the signature text used to sign this document. Read/write.

Syntax

expression .SignatureText

expression An expression that returns a SignatureInfo object.

Return Value

String

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo Methods (Office)

 Copy code hover
[image]

SignatureInfo Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
GetCertificateDetail | Displays a specified detail related to a digital certificate.
GetSignatureDetail | Displays a specified detail related to a signature.
SelectCertificateDetailByThumbprint | Displays a dialog box containing information about a digital certificate following vertification of the user from a thumbprint.
SelectSignatureCertificate | Displays a dialog box that allows users to select which signature certificate to use for signing a document.
ShowSignatureCertificate | Displays the selected or default digital certificate.


SignatureInfo.GetCertificateDetail Method (Office)

 Copy code hover
[image]

SignatureInfo.GetCertificateDetail Method (Office)
See also Send feedback

Published: July 09, 2012

Displays a specified detail related to a digital certificate.

Syntax

expression .GetCertificateDetail(certdet)

expression An expression that returns a SignatureInfo object.

Parameters

Name | Required/Optional | Data Type | Description
certdet | Required | CertificateDetail | An enumerated value specifying which certificate detail to display.

Return Value

Variant

Example

The following example gets the expiration date of the digital certificate.

VBA Copy code Copy code
Sub GetCertDetails()
Dim objSignatureInfo As SignatureInfo
Dim varDetail As Variant

strDetail = objSignatureInfo.GetCertificationDetail(certdetExpirationDate)

End Sub

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.GetSignatureDetail Method (Office)

 Copy code hover
[image]

SignatureInfo.GetSignatureDetail Method (Office)
See also Send feedback

Published: July 09, 2012

Displays a specified detail related to a signature.

Syntax

expression .GetSignatureDetail(sigdet)

expression An expression that returns a SignatureInfo object.

Parameters

Name | Required/Optional | Data Type | Description
sigdet | Required | SignatureDetail | An enumerated value specifying which signature detail to display.

Return Value

Variant

Example

The following example gets information on the suggested signer of the document.

VBA Copy code Copy code
Sub GetSigDetails()
Dim objSignatureInfo As SignatureInfo
Dim varDetail As Variant

strDetail = objSignatureInfo.GetSignatureDetail(sigdetDelSuggSigner)

End Sub

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.SelectCertificateDetailByThumbprint Method (Office)

 Copy code hover
[image]

SignatureInfo.SelectCertificateDetailByThumbprint Method (Office)
See also Send feedback

Published: July 09, 2012

Displays a dialog box containing information about a digital certificate following vertification of the user from a thumbprint.

Syntax

expression .SelectCertificateDetailByThumbprint(bstrThumbprint)

expression An expression that returns a SignatureInfo object.

Parameters

Name | Required/Optional | Data Type | Description
bstrThumbprint | Required | String | Contains information about the signer identified by the thumbprint.

Example

The following example displays a dialog box with details about the digital certificate for the user identified from a thumbprint.

VBA Copy code Copy code
Sub SelectDigCertificate(ByVal strVerificationDetail As String)
Dim objSignatureInfo As SignatureInfo
Dim objDialog As Object

objDialog = objSignatureInfo.SelectCertificateDetailByThumbprint(strVerificationDetail)

End Sub

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.SelectSignatureCertificate Method (Office)

 Copy code hover
[image]

SignatureInfo.SelectSignatureCertificate Method (Office)
See also Send feedback

Published: July 09, 2012

Displays a dialog box that allows users to select which signature certificate to use for signing a document.

Syntax

expression .SelectSignatureCertificate(ParentWindow)

expression An expression that returns a SignatureInfo object.

Parameters

Name | Required/Optional | Data Type | Description
ParentWindow | Required | IOleWindow | Contains a handle to the window containing the certificate selection dialog box.

Example

The following example displays a dialog box that allows the user to select a digital certificate.

VBA Copy code Copy code
Sub SelectDigCertificate(ByVal intHwnd As Long)
Dim objSignatureInfo As SignatureInfo
Dim objDialog As Object

objDialog = objSignatureInfo.SelectSignatureCertificate(intHwnd)

End Sub

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureInfo.ShowSignatureCertificate Method (Office)

 Copy code hover
[image]

SignatureInfo.ShowSignatureCertificate Method (Office)
See also Send feedback

Published: July 09, 2012

Displays the selected or default digital certificate.

Syntax

expression .ShowSignatureCertificate(ParentWindow)

expression An expression that returns a SignatureInfo object.

Parameters

Name | Required/Optional | Data Type | Description
ParentWindow | Required | IOleWindow | Contains the handle to the window that contains the Certificate dialog box.

Example

The following example displays a digital certificate in the window specified by the Hwnd argument.

VBA Copy code Copy code
Sub DisplayCertificate(ByVal intHwnd As Long)
Dim objSignatureInfo As SignatureInfo
Dim objDialog As Object

objDialog = objSignatureInfo.ShowSignatureCertificate(intHwnd)

End Sub

See also

Concepts

SignatureInfo Object

Other resources

SignatureInfo Object Members


SignatureProvider Object (Office)

 Copy code hover
[image]

SignatureProvider Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a signature provider add-in.

Note Note

Signature providers are implemented exclusively in custom COM add-ins and cannot be implemented in Microsoft Visual Basic for Applications (VBA).

See also

Concepts

Object Model Reference

Other resources

SignatureProvider Object Members


SignatureProvider Members (Office)

 Copy code hover
[image]

SignatureProvider Members (Office)
Send feedback

Published: July 09, 2012

Represents a signature provider add-in.

Methods

Name | Description
GenerateSignatureLineImage | Gets a signature line image.
GetProviderDetail | Queries the signature provider add-in for various details.
HashStream | Allows a signature provider add-in to create a hash value for the document that you can use to determine if the document contents were tampered with after digital signing.
NotifySignatureAdded | Used to display a dialog box informing the user that the signing process has completed and providing additional functionality for the add-in.
ShowSignatureDetails | Provides a signature povider add-in the opportunity to display details about a signed signature line and display additional stored information such as a secure time-stamp.
ShowSignatureSetup | Provides a signature provider add-in the opportunity to display the Signature Setup dialog box to the user.
ShowSigningCeremony | Provides a signature provider add-in the opportunity to display the Signature dialog box to users, allowing them to specify their identity and then be authenticated.
SignXmlDsig | Used to sign the XMLDSIG template.
VerifyXmlDsig | Verifies a signature based on the signed state of the document and the legitimacy of the certificate used for signing.


SignatureProvider Methods (Office)

 Copy code hover
[image]

SignatureProvider Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
GenerateSignatureLineImage | Gets a signature line image.
GetProviderDetail | Queries the signature provider add-in for various details.
HashStream | Allows a signature provider add-in to create a hash value for the document that you can use to determine if the document contents were tampered with after digital signing.
NotifySignatureAdded | Used to display a dialog box informing the user that the signing process has completed and providing additional functionality for the add-in.
ShowSignatureDetails | Provides a signature povider add-in the opportunity to display details about a signed signature line and display additional stored information such as a secure time-stamp.
ShowSignatureSetup | Provides a signature provider add-in the opportunity to display the Signature Setup dialog box to the user.
ShowSigningCeremony | Provides a signature provider add-in the opportunity to display the Signature dialog box to users, allowing them to specify their identity and then be authenticated.
SignXmlDsig | Used to sign the XMLDSIG template.
VerifyXmlDsig | Verifies a signature based on the signed state of the document and the legitimacy of the certificate used for signing.


SignatureProvider.GenerateSignatureLineImage Method (Office)

 Copy code hover
[image]

SignatureProvider.GenerateSignatureLineImage Method (Office)
See also Send feedback

Published: July 09, 2012

Gets a signature line image.

Syntax

expression .GenerateSignatureLineImage(siglnimg, psigsetup, psiginfo)

expression An expression that returns a SignatureProvider object.

Parameters

Name | Required/Optional | Data Type | Description
siglnimg | Required | SignatureLineImage | Contains the name if the signature line graphic.
psigsetup | Required | SignatureSetup | Specifies initial settings of the signature provider add-in.
psiginfo | Required | SignatureInfo | Specifies information about the signature provider add-in.

Remarks

The SignatureProvider object is used exclusively in custom signature provider add-ins. This method is called for each of the images that is displayed in the document's content. The method can be called asynchronously. For example, the method may be called for the "Unsigned" image and the "No-software" image directly after signature setup. The method may then be called after signing for the "Signed" image. The four images used are:

  • siglnimgSoftwareRequired: This image is displayed to the user if the signature provider add-in is not installed on the user's computer. If the user tries to sign or view a signature line, they are redirected to a provider-supplied hyperlink specified in the GetProviderDetail method.

  • siglnimgUnsigned: This image is displayed for an unsigned signature image. Basically, when a document loads with an unsigned signature line, the signature provider prompts for an up-to-date signature image and shows this image.

  • siglnimgSignedValid: This is the image that is displayed when a signature line is signed and valid (or, to be more specific, signed and the signature does not register as invalid). When the document opens, it is assumed that all signed signatures are valid until the verification process is complete, at which point a "Signed/invalid" image is displayed for the invalid signatures. Because signature verification is time-intensive, the signature verification runs in parallel with Office on a background thread. Because your add-in implements signature verification, your code runs parallel with Office and should not attempt to display UI during signing or verifying.

  • siglnimgSignedInvalid: This is the image we show when a signature line is signed but there is a problem with the signature, such as the document was modified or the user's certificate is revoked. Because your add-in implements signature verification, you can decide how and when a signature is invalid.

Example

The following example, written in C#, shows the implementation of the GenerateSignatureLineImage method in a custom signature provider project.

Copy code Copy code
 public IPictureDisp GenerateSignatureLineImage(SignatureLineImage siglnimg, SignatureSetup sigsetup, SignatureInfo siginfo, object xmldsigStream)
 {
 IPictureDisp sigline = null;

 System.Drawing.Bitmap draw = new System.Drawing.Bitmap(200, 100);
 Graphics g = Graphics.FromImage(draw);
 g.DrawRectangle(new Pen(Color.Gray, 2), 0, 0, 200, 100);

 if (siglnimg == SignatureLineImage.siglnimgUnsigned)
 {
 g.FillRectangle(new SolidBrush(Color.LightSlateGray), 2, 2, 196, 96);
 g.DrawString("Requested Signature", new System.Drawing.Font("Verdana", 10), new SolidBrush(Color.Yellow), new PointF(20, 20));
 g.DrawString(sigsetup.SuggestedSigner, new System.Drawing.Font("Courier", 8), new SolidBrush(Color.Yellow), new PointF(20, 50));
 }
 else if (siglnimg == SignatureLineImage.siglnimgSignedValid)
 {
 g.FillRectangle(new SolidBrush(Color.LightSlateGray), 2, 2, 196, 96);
 g.DrawString("Valid Signature", new System.Drawing.Font("Verdana", 10), new SolidBrush(Color.LimeGreen), new PointF(20, 20));
 g.DrawString(sigsetup.SuggestedSigner, new System.Drawing.Font("Courier", 8), new SolidBrush(Color.LimeGreen), new PointF(20, 50));
 }
 else if (siglnimg == SignatureLineImage.siglnimgSignedInvalid)
 {
 g.FillRectangle(new SolidBrush(Color.LightSlateGray), 2, 2, 196, 96);
 g.DrawString("Invalid Signature", new System.Drawing.Font("Verdana", 10), new SolidBrush(Color.Red), new PointF(20, 20));
 g.DrawString(sigsetup.SuggestedSigner, new System.Drawing.Font("Courier", 8), new SolidBrush(Color.Red), new PointF(20, 50));
 }
 else if (siglnimg == SignatureLineImage.siglnimgSoftwareRequired)
 {
 g.FillRectangle(new SolidBrush(Color.LightSlateGray), 2, 2, 196, 96);
 g.DrawString("Software Required", new System.Drawing.Font("Verdana", 10), new SolidBrush(Color.AliceBlue), new PointF(20, 20));
 }
 else
 {
 throw new NotImplementedException();
 }

 System.IntPtr hbitmap = draw.GetHbitmap(Color.Green);
 Image img = Image.FromHbitmap(hbitmap);

 sigline = (IPictureDisp)AxHost2.GetIPictureDispFromPicture(img);

 return sigline;

 }
Note Note

Signature providers are implemented exclusively in custom COM add-ins and cannot be implemented in Microsoft Visual Basic for Applications (VBA).

See also

Concepts

SignatureProvider Object

Other resources

SignatureProvider Object Members


SignatureProvider.GetProviderDetail Method (Office)

 Copy code hover
[image]

SignatureProvider.GetProviderDetail Method (Office)
See also Send feedback

Published: July 09, 2012

Queries the signature provider add-in for various details.

Syntax

expression .GetProviderDetail(sigprovdet)

expression An expression that returns a SignatureProvider object.

Parameters

Name | Required/Optional | Data Type | Description
sigprovdet | Required | SignatureProviderDetail | Contains an enumerated value representing the type of information to query the add-in for.

Return Value

Variant

Remarks

The SignatureProvider object is used exclusively in custom signature provider add-ins. This method is used to query the add-in for three pieces of information:

  • What hash algorithm does the add-in support?

  • Is the add-in only a user interface (UI) or does it support hashing and verification? If TRUE is returned, Microsoft Office does not call the add-in to hash or verify, only to display the UI.

  • What URL should the add-in provide for users if they are missing the signature add-in?

Example

The following example, written in C#, shows the implementation of the GetProviderDetail method in a custom signature provider project.

Copy code Copy code
 public object GetProviderDetail(SignatureProviderDetail sigProvDetail)
 {
 switch (sigProvDetail)
 {
 case Microsoft.Office.Core.SignatureProviderDetail.sigprovdetHashAlgorithm:
 return this.HashAlgorithmIdentifier;

 case Microsoft.Office.Core.SignatureProviderDetail.sigprovdetUIOnly:
 return false;

 case Microsoft.Office.Core.SignatureProviderDetail.sigprovdetUrl:
 return this.ProviderUrl;

 default:
 return null;
 }
 }
Note Note

Signature providers are implemented exclusively in custom COM add-ins and cannot be implemented in Microsoft Visual Basic for Applications (VBA).

See also

Concepts

SignatureProvider Object

Other resources

SignatureProvider Object Members


SignatureProvider.HashStream Method (Office)

 Copy code hover
[image]

SignatureProvider.HashStream Method (Office)
See also Send feedback

Published: July 09, 2012

Allows a signature provider add-in to create a hash value for the document that you can use to determine if the document contents were tampered with after digital signing.

Syntax

expression .HashStream(QueryContinue, Stream)

expression An expression that returns a SignatureProvider object.

Parameters

Name | Required/Optional | Data Type | Description
QueryContinue | Required | IQueryContinue | Provides a way to query the host application for permission to continue the hashing process.
Stream | Required | IStream | Contains the data stream.

Return Value

Byte

Remarks

The SignatureProvider object is used exclusively in custom signature provider add-ins. This method is called once per signature data stream in a document. The return value is an array of bytes representing the hash value computed using the hash algorithm.

Example

The following example gets the hash value of a data stream.

Copy code Copy code
 public Array HashStream(object queryContinue, object stream)
 {
 using (COMStream comstream = new COMStream(stream))
 {
 using (HashAlgorithm hashalg = HashAlgorithm.Create(this.HashAlgorithmName))
 {
 return hashalg.ComputeHash(comstream);
 }
 }
 }
Note Note

Signature providers are implemented exclusively in custom COM add-ins and cannot be implemented in Microsoft Visual Basic for Applications (VBA).

See also

Concepts

SignatureProvider Object

Other resources

SignatureProvider Object Members


SignatureProvider.NotifySignatureAdded Method (Office)

 Copy code hover
[image]

SignatureProvider.NotifySignatureAdded Method (Office)
See also Send feedback

Published: July 09, 2012

Used to display a dialog box informing the user that the signing process has completed and providing additional functionality for the add-in.

Syntax

expression .NotifySignatureAdded(ParentWindow, psigsetup, psiginfo)

expression An expression that returns a SignatureProvider object.

Parameters

Name | Required/Optional | Data Type | Description
ParentWindow | Required | IOleWindow | Allows the host application to obtain the handle to the window containing the displayed dialog box.
psigsetup | Required | SignatureSetup | Contains initial settings of the signature provider.
psiginfo | Required | SignatureInfo | Contains information about the signature provider add-in.

Remarks

This method is called when the signing process has completed. Allows a signature provider add-in the ability to add additional functionality to the add-in. For example, if you wanted to offer an archive service where a user could upload their signed document, you could use this method to initiate that process.

Example

The following example, written in C#, shows the implementation of the NotifySignatureAdded method in a custom signature provider project.

Copy code Copy code
 public void NotifySignatureAdded(object parentWindow, SignatureSetup sigsetup, SignatureInfo siginfo)
 {
 using (Win32WindowFromOleWindow window = new Win32WindowFromOleWindow(parentWindow))
 {
 MessageBox.Show(window, "Signature has been applied", "Signing Ceremony", MessageBoxButtons.OK);
 }
 }
Note Note

Signature providers are implemented exclusively in custom COM add-ins and cannot be implemented in Microsoft Visual Basic for Applications (VBA).

See also

Concepts

SignatureProvider Object

Other resources

SignatureProvider Object Members


SignatureProvider.ShowSignatureDetails Method (Office)

 Copy code hover
[image]

SignatureProvider.ShowSignatureDetails Method (Office)
See also Send feedback

Published: July 09, 2012

Provides a signature povider add-in the opportunity to display details about a signed signature line and display additional stored information such as a secure time-stamp.

Syntax

expression .ShowSignatureDetails(ParentWindow, psigsetup, psiginfo, XmlDsigStream, pcontverres, pcertverres)

expression An expression that returns a SignatureProvider object.

Parameters

Name | Required/Optional | Data Type | Description
ParentWindow | Required | IOleWindow | Contains the handle to the window containing the signature details.
psigsetup | Required | SignatureSetup | Specifies initial settings of the signature provider.
psiginfo | Required | SignatureInfo | Specifies information about the signed signature line.
XmlDsigStream | Required | IStream | Represents a steam of data or binary large object of XML.
pcontverres | Required | ContentVerificationResults | Contains a value representing the results of verificating the signature content.
pcertverres | Required | CertificateVerificationResults | Contains a value representing the results of verificating the signing certification.

Example

The following example, written in C#, shows the implementation of the ShowSignatureDetails method in a custom signature provider project.

Copy code Copy code
 public void ShowSignatureDetails(object parentWindow, SignatureSetup sigsetup, SignatureInfo siginfo, object xmldsigStream, ref ContentVerificationResults contverresults, ref CertificateVerificationResults certverresults)
 {
 using (Win32WindowFromOleWindow window = new Win32WindowFromOleWindow(parentWindow))
 {
 using (SigningCeremonyForm signForm = new SigningCeremonyForm(sigsetup, siginfo))
 {
 signForm.ShowDialog(window);
 }
 }
 }
Note Note

Signature providers are implemented exclusively in custom COM add-ins and cannot be implemented in Microsoft Visual Basic for Applications (VBA).

See also

Concepts

SignatureProvider Object

Other resources

SignatureProvider Object Members


SignatureProvider.ShowSignatureSetup Method (Office)

 Copy code hover
[image]

SignatureProvider.ShowSignatureSetup Method (Office)
See also Send feedback

Published: July 09, 2012

Provides a signature provider add-in the opportunity to display the Signature Setup dialog box to the user.

Syntax

expression .ShowSignatureSetup(ParentWindow, psigsetup)

expression An expression that returns a SignatureProvider object.

Parameters

Name | Required/Optional | Data Type | Description
ParentWindow | Required | IOleWindow | Contains the handle to the window containing the Signature Setup dialog box.
psigsetup | Required | SignatureSetup | Specifies initial settings of the signature provider.

Remarks

This method is used for both the insertion time configuration process and if a user later wants to re-configure the signature line. You display the Signature Setup dialog box during this callback and wait for the user to select OK or Cancel. It is not necessary to display a dialog box for signature setup unless you specifically need information from the author about the signature line. If you can provide all of the necessary details back to Microsoft Office without user input, then no dialog is necessary.

Example

The following example, written in C#, shows the implementation of the ShowSignatureSetup method in a custom signature provider project.

Copy code Copy code
 public void ShowSignatureSetup(object parentWindow, SignatureSetup sigsetup)
 {
 bool firstInit = string.IsNullOrEmpty(sigsetup.AdditionalXml);
 if (sigsetup != null && !sigsetup.ReadOnly && firstInit)
 {
 sigsetup.SigningInstructions = "Please sign this document.";
 sigsetup.ShowSignDate = true;
 sigsetup.AdditionalXml = "<TestSignatureData />";
 }

 using (Win32WindowFromOleWindow window = new Win32WindowFromOleWindow(parentWindow))
 {
 using (SignatureSetupForm sigsetupForm = new SignatureSetupForm(sigsetup))
 {
 sigsetupForm.ShowDialog(window);
 if (!sigsetupForm.success && firstInit)
 throw new System.Runtime.InteropServices.COMException("Canceled", -2147467260 /*E_ABORT*/);
 }
 }
 }
Note Note

Signature providers are implemented exclusively in custom COM add-ins and cannot be implemented in Microsoft Visual Basic for Applications (VBA).

See also

Concepts

SignatureProvider Object

Other resources

SignatureProvider Object Members


SignatureProvider.ShowSigningCeremony Method (Office)

 Copy code hover
[image]

SignatureProvider.ShowSigningCeremony Method (Office)
See also Send feedback

Published: July 09, 2012

Provides a signature provider add-in the opportunity to display the Signature dialog box to users, allowing them to specify their identity and then be authenticated.

Syntax

expression .ShowSigningCeremony(ParentWindow, psigsetup, psiginfo)

expression An expression that returns a SignatureProvider object.

Parameters

Name | Required/Optional | Data Type | Description
ParentWindow | Required | IOleWindow | Contains the handle to the window containing the Signature dialog box.
psigsetup | Required | SignatureSetup | Specifies initial settings of the signature provider.
psiginfo | Required | SignatureInfo | Specifies information about the signature provider.

Remarks

This method is internally called by the Microsoft Office application when the user is attempting to sign a signature line, or if the add-in has called the Sign method in the Office application's object model on a SignatureLine object.

Example

The following example, written in C#, shows the implementation of the ShowSigningCeremony method in a custom signature provider project.

Copy code Copy code
 public void ShowSigningCeremony(object parentWindow, SignatureSetup sigsetup, SignatureInfo siginfo)
 {
 using (Win32WindowFromOleWindow window = new Win32WindowFromOleWindow(parentWindow))
 {
 if (!((bool) siginfo.GetCertificateDetail(CertificateDetail.certdetAvailable)))
 {
 MessageBox.Show(window, "You need a digital certificate to sign this document", "Signing Ceremony", MessageBoxButtons.OK);
 throw new System.Runtime.InteropServices.COMException("Canceled", -2147467260 /*E_ABORT*/);
 }

 using (SigningCeremonyForm signForm = new SigningCeremonyForm(sigsetup, siginfo))
 {
 signForm.ShowDialog(window);
 if (!signForm.success)
 throw new System.Runtime.InteropServices.COMException("Cancelled", -2147467260 /*E_ABORT*/);
 }
 }
 }
Note Note

Signature providers are implemented exclusively in custom COM add-ins and cannot be implemented in Microsoft Visual Basic for Applications (VBA).

See also

Concepts

SignatureProvider Object

Other resources

SignatureProvider Object Members


SignatureProvider.SignXmlDsig Method (Office)

 Copy code hover
[image]

SignatureProvider.SignXmlDsig Method (Office)
See also Send feedback

Published: July 09, 2012

Used to sign the XMLDSIG template.

Syntax

expression .SignXmlDsig(QueryContinue, psigsetup, psiginfo, XmlDsigStream)

expression An expression that returns a SignatureProvider object.

Parameters

Name | Required/Optional | Data Type | Description
QueryContinue | Required | IQueryContinue | Provides a way to query the host application for permission to continue the verification operation.
psigsetup | Required | SignatureSetup | Specifies configuration information about a signature line.
psiginfo | Required | SignatureInfo | Specifies information captured from the signing ceremony.
XmlDsigStream | Required | IStream | Represents a steam of data containing XML, which represents an XMLDSIG object.

Remarks

XMLDSIG is a standards-based signature format (http://www.w3.org/TR/xmldsig-core/), verifiable by third parties. This is the default format for signatures in the Microsoft Office.

Example

The following example, written in C#, shows the implementation of the SignXmlDsig method in a custom signature provider project.

Copy code Copy code
 public void SignXmlDsig(object queryContinue, SignatureSetup sigsetup, SignatureInfo siginfo, object xmldsigStream)
 {
 using (COMStream comstream = new COMStream(xmldsigStream))
 {
 XmlDocument xmldsig = new XmlDocument();
 xmldsig.PreserveWhitespace = true;
 xmldsig.Load(comstream);

 XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmldsig.NameTable);
 nsmgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

 XmlElement signature = xmldsig.DocumentElement;
 SignedXml signedXml = new SignedXml();
 signedXml.LoadXml(signature);

 // Cert
 X509Certificate2 cert = TestSignatureProvider.GetSigningCertificate(siginfo);
 KeyInfo keyInfo = new KeyInfo();
 if (cert.PrivateKey is RSA)
 keyInfo.AddClause(new RSAKeyValue((RSA) cert.PrivateKey));
 else if (cert.PrivateKey is DSA)
 keyInfo.AddClause(new DSAKeyValue((DSA) cert.PrivateKey));
 keyInfo.AddClause(new KeyInfoX509Data(cert));
 signedXml.SigningKey = cert.PrivateKey;
 signedXml.KeyInfo = keyInfo;

 // Compute signature
 signedXml.ComputeSignature();

 // Copy data from signed signature
 // REVIEW: Cleaner way to do this?
 string[] xpathsToCopy = new string[]
 {
 "./ds:SignedInfo",
 "./ds:SignatureValue",
 "./ds:KeyInfo",
 };
 XmlElement signedSignature = signedXml.GetXml();
 foreach (string xpathToCopy in xpathsToCopy)
 {
 signature.ReplaceChild(
 xmldsig.ImportNode(signedSignature.SelectSingleNode(xpathToCopy, nsmgr), true),
 signature.SelectSingleNode(xpathToCopy, nsmgr));
 }

 // Save signature back to stream
 comstream.SetLength(0);
 comstream.Position = 0;
 xmldsig.Save(new XmlTextWriter(comstream, new UTF8Encoding(false)));
 }
 }
Note Note

Signature providers are implemented exclusively in custom COM add-ins created in managed and unmanaged code and cannot be implemented in Microsoft Visual Basic for Applications (VBA).

See also

Concepts

SignatureProvider Object

Other resources

SignatureProvider Object Members


SignatureProvider.VerifyXmlDsig Method (Office)

 Copy code hover
[image]

SignatureProvider.VerifyXmlDsig Method (Office)
See also Send feedback

Published: July 09, 2012

Verifies a signature based on the signed state of the document and the legitimacy of the certificate used for signing.

Syntax

expression .VerifyXmlDsig(QueryContinue, psigsetup, psiginfo, XmlDsigStream, pcontverres, pcertverres)

expression An expression that returns a SignatureProvider object.

Parameters

Name | Required/Optional | Data Type | Description
QueryContinue | Required | IQueryContinue | Provides a way to query the host application for permission to continue the verification operation.
psigsetup | Required | SignatureSetup | Specifies configuration information about a signature line.
psiginfo | Required | SignatureInfo | Specifies information captured from the signing ceremony.
XmlDsigStream | Required | IStream | Represents a steam of data containing XML, which represents an XMLDSIG object.
pcontverres | Required | ContentVerificationResults | Specifies the status of the signature verification action.
pcertverres | Required | CertificateVerificationResults | Specifies the status of the signing certificate verification.

Remarks

XMLDSIG is a standards-based signature format (http://www.w3.org/TR/xmldsig-core/), verifiable by third parties. This is the default format for signatures in Microsoft Office.

Example

The following example, written in C#, shows the implementation of the VerifyXmlDsig method in a custom signature provider project.

Copy code Copy code
 public void VerifyXmlDsig(object queryContinue, SignatureSetup sigsetup, SignatureInfo siginfo, object xmldsigStream, ref ContentVerificationResults contverresults, ref CertificateVerificationResults certverresults)
 {
 using (COMStream comstream = new COMStream(xmldsigStream))
 {
 XmlDocument xmldsig = new XmlDocument();
 xmldsig.PreserveWhitespace = true;
 xmldsig.Load(comstream);

 XmlElement signature = xmldsig.DocumentElement;
 SignedXml signedXml = new SignedXml();
 signedXml.LoadXml(signature);

 contverresults = signedXml.CheckSignature() ?
 Microsoft.Office.Core.ContentVerificationResults.contverresValid :
 Microsoft.Office.Core.ContentVerificationResults.contverresModified;
 }
 }
Note Note

Signature providers are implemented exclusively in custom COM add-ins created in managed and unmanaged code and cannot be implemented in Microsoft Visual Basic® for Applications (VBA).

See also

Concepts

SignatureProvider Object

Other resources

SignatureProvider Object Members


SignatureSet Object (Office)

 Copy code hover
[image]

SignatureSet Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of Signature objects that correspond to the digital signature attached to a document.

Remarks

Use the Signatures property of the Document object to return a SignatureSet collection; for example:

Copy code Copy code
Set sigs = ActiveDocument.Signatures

You can add a Signature object to a SignatureSet collection using the Add method and you can return an existing member using the Item method. The AddSignatureLine method also adds a Signature object to the collection. Also see the Subset property, which acts as a filter for whether certain Signature objects appear in the collection. To remove a Signature from a SignatureSet collection, use the Delete method of the Signature object.

Example

The following example prompts the user to select a digital signature with which to sign the active document in Microsoft Word. To use this example, open a document in Word and pass this function the name of a certificate issuer and the name of a certificate signer that match the Issued By and Issued To fields of a digital certificate in the Digital Certificates dialog box. This example will test to make sure that the digital signature that the user selects meets certain criteria, such as not having expired, before the new signature is committed to the disk.

Copy code Copy code
Function AddSignature(ByVal strIssuer As String, _
 strSigner As String) As Boolean

 Dim sig As Signature

 'Display the dialog box that lets the
 'user select a digital signature.
 'If the user selects a signature, then
 'it is added to the Signatures
 'collection. If the user doesn't, then
 'an error is returned.
 Set sig = ActiveDocument.Signatures.Add

 'Test several properties before committing the Signature object to disk.
 If sig.Issuer = strIssuer And _
 sig.Signer = strSigner And _
 sig.IsCertificateExpired = False And _
 sig.IsCertificateRevoked = False And _
 sig.IsValid = True Then

 MsgBox "Signed"
 AddSignature = True
 'Otherwise, remove the Signature object from the SignatureSet collection.
 Else
 sig.Delete
 MsgBox "Not signed"
 AddSignature = False
 End If

End Function

See also

Concepts

Object Model Reference

Other resources

SignatureSet Object Members


SignatureSet Members (Office)

 Copy code hover
[image]

SignatureSet Members (Office)
Send feedback

Published: July 09, 2012

A collection of Signature objects that correspond to the digital signature attached to a document.

Methods

Name | Description
AddNonVisibleSignature | Creates a signature packet when digitally signing a document.
AddSignatureLine | Adds lines to a document where signatures are collected.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SignatureSet object (you can use this property with an Automation object to return that object's container application). Read-only.
CanAddSignatureLine | Gets a Boolean value indicating whether you can add a signature line to a document. Read-only.
Count | Gets a Long indicating the number of items in the SignatureSet object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SignatureSet object was created. Read-only.
Item | Gets a Signature object that corresponds to one of the digital signatures with which the document is currently signed. Read-only.
Parent | Gets the Parent object for the SignatureSet object. Read-only.
ShowSignaturesPane | Gets or sets a Boolean value indicating whether the Signature task pane should be displayed. Read/write.
Subset | Gets or sets a value that acts as a filter on the available Signature objects for a document. Read/write.


SignatureSet Properties (Office)

 Copy code hover
[image]

SignatureSet Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SignatureSet object (you can use this property with an Automation object to return that object's container application). Read-only.
CanAddSignatureLine | Gets a Boolean value indicating whether you can add a signature line to a document. Read-only.
Count | Gets a Long indicating the number of items in the SignatureSet object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SignatureSet object was created. Read-only.
Item | Gets a Signature object that corresponds to one of the digital signatures with which the document is currently signed. Read-only.
Parent | Gets the Parent object for the SignatureSet object. Read-only.
ShowSignaturesPane | Gets or sets a Boolean value indicating whether the Signature task pane should be displayed. Read/write.
Subset | Gets or sets a value that acts as a filter on the available Signature objects for a document. Read/write.


SignatureSet.Application Property (Office)

 Copy code hover
[image]

SignatureSet.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SignatureSet object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a SignatureSet object.

Return Value

Object

See also

Concepts

SignatureSet Object

Other resources

SignatureSet Object Members


SignatureSet.CanAddSignatureLine Property (Office)

 Copy code hover
[image]

SignatureSet.CanAddSignatureLine Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value indicating whether you can add a signature line to a document. Read-only.

Syntax

expression .CanAddSignatureLine

expression An expression that returns a SignatureSet object.

Return Value

Boolean

See also

Concepts

SignatureSet Object

Other resources

SignatureSet Object Members


SignatureSet.Count Property (Office)

 Copy code hover
[image]

SignatureSet.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the SignatureSet object. Read-only.

Syntax

expression .Count

expression A variable that represents a SignatureSet object.

Return Value

Long

See also

Concepts

SignatureSet Object

Other resources

SignatureSet Object Members


SignatureSet.Creator Property (Office)

 Copy code hover
[image]

SignatureSet.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SignatureSet object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a SignatureSet object.

Return Value

Long

See also

Concepts

SignatureSet Object

Other resources

SignatureSet Object Members


SignatureSet.Item Property (Office)

 Copy code hover
[image]

SignatureSet.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Signature object that corresponds to one of the digital signatures with which the document is currently signed. Read-only.

Syntax

expression .Item(iSig)

expression Required. A variable that represents a SignatureSet object.

Parameters

Name | Required/Optional | Data Type | Description
iSig | Required | Long | Determines which Signature object to return.

See also

Concepts

SignatureSet Object

Other resources

SignatureSet Object Members


SignatureSet.Parent Property (Office)

 Copy code hover
[image]

SignatureSet.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the SignatureSet object. Read-only.

Syntax

expression .Parent

expression A variable that represents a SignatureSet object.

Return Value

Object

See also

Concepts

SignatureSet Object

Other resources

SignatureSet Object Members


SignatureSet.ShowSignaturesPane Property (Office)

 Copy code hover
[image]

SignatureSet.ShowSignaturesPane Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a Boolean value indicating whether the Signature task pane should be displayed. Read/write.

Syntax

expression .ShowSignaturesPane

expression An expression that returns a SignatureSet object.

Return Value

Boolean

See also

Concepts

SignatureSet Object

Other resources

SignatureSet Object Members


SignatureSet.Subset Property (Office)

 Copy code hover
[image]

SignatureSet.Subset Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value that acts as a filter on the available Signature objects for a document. Read/write.

Syntax

expression .Subset

expression An expression that returns a SignatureSet object.

Return Value

MsoSignatureSubset

See also

Concepts

SignatureSet Object

Other resources

SignatureSet Object Members


SignatureSet Methods (Office)

 Copy code hover
[image]

SignatureSet Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
AddNonVisibleSignature | Creates a signature packet when digitally signing a document.
AddSignatureLine | Adds lines to a document where signatures are collected.


SignatureSet.AddNonVisibleSignature Method (Office)

 Copy code hover
[image]

SignatureSet.AddNonVisibleSignature Method (Office)
See also Send feedback

Published: July 09, 2012

Creates a signature packet when digitally signing a document.

Syntax

expression .AddNonVisibleSignature(varSigProv)

expression An expression that returns a SignatureSet object.

Parameters

Name | Required/Optional | Data Type | Description
varSigProv | Optional | Variant | Represents the ID of the signature provider.

Return Value

Signature

Remarks

To provide an entry point to trigger this method, you need to create a user interface with the signature provider add-in. This entry point is typically provided to the user as a menu option.

Example

The following function uses the signature provider ID argument to create a signature packet when digitally signing a document.

VBA Copy code Copy code
Function CreateSignature(ByVal varSigProviderID As Variant) As Signature
Dim objSignatureSet As SignatureSet
Dim objSignature As Signature

objSignature = objSignatureSet.AddNonVisibleSignature(varSigProviderID)
CreateSignature = objSignature

End Function

See also

Concepts

SignatureSet Object

Other resources

SignatureSet Object Members


SignatureSet.AddSignatureLine Method (Office)

 Copy code hover
[image]

SignatureSet.AddSignatureLine Method (Office)
See also Send feedback

Published: July 09, 2012

Adds lines to a document where signatures are collected.

Syntax

expression .AddSignatureLine(varSigProv)

expression An expression that returns a SignatureSet object.

Parameters

Name | Required/Optional | Data Type | Description
varSigProv | Optional | Variant | Represents the ID of the signature provider.

Return Value

Signature

Remarks

After the line is added, the author of the document can add the necessary information so that each signature line shows the name and (optionally) the title of the person who should sign. When a user opens the document, Microsoft Office recognizes that one or more signature lines are present, but blank. Office then alerts the user that they need to sign this document and helps them find where in the document the requested signatures are located.

Example

The procedure in the following example receives the ID of a signature provider and, as long as the document is not read-only, adds a signature line.

VBA Copy code Copy code
Function InsertSignatureLines(ByVal SignProviderID As Variant) As Signature
Dim objSignature As Signature

If CanAddSignatureLine Then
 objSignature = AddSignatureLine(SignProviderID)
End If

InsertSignatureLines = objSignature

End Function

See also

Concepts

SignatureSet Object

Other resources

SignatureSet Object Members


SignatureSetup Object (Office)

 Copy code hover
[image]

SignatureSetup Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the information used to set up a signature packet.

Example

The following example sets various properties of the SignatureSetup object for a signature packet.

VBA Copy code Copy code
Dim objSigSetup As SignatureSetup
With objSigSetup
.AllowComments = True
.ShowSignDate = True
.SigningInstructions = "Please sign this document."
.SuggestedSignerEmail = "jdow@example.com"
Next

See also

Concepts

Object Model Reference

Other resources

SignatureSetup Object Members


SignatureSetup Members (Office)

 Copy code hover
[image]

SignatureSetup Members (Office)
Send feedback

Published: July 09, 2012

Represents the information used to set up a signature packet.

Properties

Name | Description
AdditionalXml | Gets or sets any additional XML information added to the signature during setup. Read/write.
AllowComments | Gets or sets a Boolean value specifying whether the signer can enter comments in the Sign dialog box. Read/write.
Application | Gets an Application object that represents the container application for the SignatureSetup object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SignatureSetup object was created. Read-only.
Id | Gets the ID of the signature provider for a document. Read-only.
ReadOnly | Gets a Boolean value indicating whether the SignatureSetup object is read-only. Read-only.
ShowSignDate | Gets or sets a Boolean value indicating whether the date the document was signed should be displayed. Read/write.
SignatureProvider | Gets a value identifying an installed signature provider add-in. Read-only.
SigningInstructions | Gets or sets the instructions for signing the document. Read/write.
SuggestedSigner | Gets or sets the name of the principle signer of the document. Read/write.
SuggestedSignerEmail | Gets or sets the e-mail address of the signer of the document. Read/write.
SuggestedSignerLine2 | Gets or sets the second line of suggested signer information (for example, title). Read/write.


SignatureSetup Properties (Office)

 Copy code hover
[image]

SignatureSetup Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
AdditionalXml | Gets or sets any additional XML information added to the signature during setup. Read/write.
AllowComments | Gets or sets a Boolean value specifying whether the signer can enter comments in the Sign dialog box. Read/write.
Application | Gets an Application object that represents the container application for the SignatureSetup object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SignatureSetup object was created. Read-only.
Id | Gets the ID of the signature provider for a document. Read-only.
ReadOnly | Gets a Boolean value indicating whether the SignatureSetup object is read-only. Read-only.
ShowSignDate | Gets or sets a Boolean value indicating whether the date the document was signed should be displayed. Read/write.
SignatureProvider | Gets a value identifying an installed signature provider add-in. Read-only.
SigningInstructions | Gets or sets the instructions for signing the document. Read/write.
SuggestedSigner | Gets or sets the name of the principle signer of the document. Read/write.
SuggestedSignerEmail | Gets or sets the e-mail address of the signer of the document. Read/write.
SuggestedSignerLine2 | Gets or sets the second line of suggested signer information (for example, title). Read/write.


SignatureSetup.AdditionalXml Property (Office)

 Copy code hover
[image]

SignatureSetup.AdditionalXml Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets any additional XML information added to the signature during setup. Read/write.

Syntax

expression .AdditionalXml

expression An expression that returns a SignatureSetup object.

Return Value

String

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SignatureSetup.AllowComments Property (Office)

 Copy code hover
[image]

SignatureSetup.AllowComments Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a Boolean value specifying whether the signer can enter comments in the Sign dialog box. Read/write.

Syntax

expression .AllowComments

expression An expression that returns a SignatureSetup object.

Return Value

Boolean

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SignatureSetup.Application Property (Office)

 Copy code hover
[image]

SignatureSetup.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SignatureSetup object. Read-only.

Syntax

expression .Application

expression An expression that returns a SignatureSetup object.

Return Value

Object

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SignatureSetup.Creator Property (Office)

 Copy code hover
[image]

SignatureSetup.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SignatureSetup object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a SignatureSetup object.

Return Value

Long

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SignatureSetup.Id Property (Office)

 Copy code hover
[image]

SignatureSetup.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the ID of the signature provider for a document. Read-only.

Syntax

expression .Id

expression An expression that returns a SignatureSetup object.

Return Value

String

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SignatureSetup.ReadOnly Property (Office)

 Copy code hover
[image]

SignatureSetup.ReadOnly Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Boolean value indicating whether the SignatureSetup object is read-only. Read-only.

Syntax

expression .ReadOnly

expression An expression that returns a SignatureSetup object.

Return Value

Boolean

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SignatureSetup.ShowSignDate Property (Office)

 Copy code hover
[image]

SignatureSetup.ShowSignDate Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a Boolean value indicating whether the date the document was signed should be displayed. Read/write.

Syntax

expression .ShowSignDate

expression An expression that returns a SignatureSetup object.

Return Value

Boolean

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SignatureSetup.SignatureProvider Property (Office)

 Copy code hover
[image]

SignatureSetup.SignatureProvider Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a value identifying an installed signature provider add-in. Read-only.

Syntax

expression .SignatureProvider

expression An expression that returns a SignatureSetup object.

Return Value

String

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SignatureSetup.SigningInstructions Property (Office)

 Copy code hover
[image]

SignatureSetup.SigningInstructions Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the instructions for signing the document. Read/write.

Syntax

expression .SigningInstructions

expression An expression that returns a SignatureSetup object.

Return Value

String

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SignatureSetup.SuggestedSigner Property (Office)

 Copy code hover
[image]

SignatureSetup.SuggestedSigner Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the name of the principle signer of the document. Read/write.

Syntax

expression .SuggestedSigner

expression An expression that returns a SignatureSetup object.

Return Value

String

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SignatureSetup.SuggestedSignerEmail Property (Office)

 Copy code hover
[image]

SignatureSetup.SuggestedSignerEmail Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the e-mail address of the signer of the document. Read/write.

Syntax

expression .SuggestedSignerEmail

expression An expression that returns a SignatureSetup object.

Return Value

String

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SignatureSetup.SuggestedSignerLine2 Property (Office)

 Copy code hover
[image]

SignatureSetup.SuggestedSignerLine2 Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the second line of suggested signer information (for example, title). Read/write.

Syntax

expression .SuggestedSignerLine2

expression An expression that returns a SignatureSetup object.

Return Value

String

See also

Concepts

SignatureSetup Object

Other resources

SignatureSetup Object Members


SmartArt Object (Office)

 Copy code hover
[image]

SmartArt Object (Office)
See also Send feedback

Published: July 09, 2012

The top level class for interacting with a SmartArt graphic.

Version Information

Version Added: Office 2010

Example

The following code adds a top-level node to the bulleted text pane.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.Nodes.Add

See also

Concepts

Object Model Reference

Other resources

SmartArt Object Members


SmartArt Members (Office)

 Copy code hover
[image]

SmartArt Members (Office)
Send feedback

Published: July 09, 2012

The top level class for interacting with a SmartArt graphic.

Methods

Name | Description
Reset | Resets the SmartArt graphic to its original state.

Properties

Name | Description
AllNodes | Retrieves a SmartArtNodes object containing all of the nodes within the SmartArt diagram. Read-only
Application | Gets an Application object that represents the container application for the SmartArt object. Read-only
Color | Retrieves or sets the Smart Art color style applied to the Smart Art graphic. Read/write
Creator | Gets a 32-bit integer that indicates the application in which the SmartArt object was created. Read-only
Layout | Retrieves or sets the Smart Art layout associated with the Smart Art graphic. Read/write
Nodes | Retrieves the children of the root node of the SmartArt diagram. Read-only
Parent | Returns the calling object. Read-only
QuickStyle | Retrieves or sets the SmartArt quick style applied to the SmartArt graphic. Read/write
Reverse | Gets or sets the state of the SmartArt diagram with regard to (left-to-right) LTR or (right-to-left) RTL, if the diagram supports reversal. Read/write


SmartArt Properties (Office)

 Copy code hover
[image]

SmartArt Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
AllNodes | Retrieves a SmartArtNodes object containing all of the nodes within the SmartArt diagram. Read-only
Application | Gets an Application object that represents the container application for the SmartArt object. Read-only
Color | Retrieves or sets the Smart Art color style applied to the Smart Art graphic. Read/write
Creator | Gets a 32-bit integer that indicates the application in which the SmartArt object was created. Read-only
Layout | Retrieves or sets the Smart Art layout associated with the Smart Art graphic. Read/write
Nodes | Retrieves the children of the root node of the SmartArt diagram. Read-only
Parent | Returns the calling object. Read-only
QuickStyle | Retrieves or sets the SmartArt quick style applied to the SmartArt graphic. Read/write
Reverse | Gets or sets the state of the SmartArt diagram with regard to (left-to-right) LTR or (right-to-left) RTL, if the diagram supports reversal. Read/write


SmartArt.AllNodes Property (Office)

 Copy code hover
[image]

SmartArt.AllNodes Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves a SmartArtNodes object containing all of the nodes within the SmartArt diagram. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .AllNodes

expression An expression that returns a SmartArt object.

Remarks

The nodes are retrieved in order, independent of data model. For example, the following data model would retrieve the nodes in order A, B, C, D, E, F.

  • A

    • B

      • C

    • D

      • E

  • F

Example

The following example sets the text inside the first node.

VBA Copy code Copy code
smartart.AllNodes(1).TextFrame2.TextRange.Text="Node 1"

See also

Concepts

SmartArt Object

Other resources

SmartArt Object Members


SmartArt.Application Property (Office)

 Copy code hover
[image]

SmartArt.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SmartArt object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a SmartArt object.

See also

Concepts

SmartArt Object

Other resources

SmartArt Object Members


SmartArt.Color Property (Office)

 Copy code hover
[image]

SmartArt.Color Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves or sets the Smart Art color style applied to the Smart Art graphic. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Color

expression An expression that returns a SmartArt object.

Example

The following code sets the color scheme of the Smart Art diagram.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.Color = Application.SmartArtColors(1)

See also

Concepts

SmartArt Object

Other resources

SmartArt Object Members


SmartArt.Creator Property (Office)

 Copy code hover
[image]

SmartArt.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SmartArt object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a SmartArt object.

See also

Concepts

SmartArt Object

Other resources

SmartArt Object Members


SmartArt.Layout Property (Office)

 Copy code hover
[image]

SmartArt.Layout Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves or sets the Smart Art layout associated with the Smart Art graphic. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Layout

expression An expression that returns a SmartArt object.

Example

The following code sets the Smart Art layout.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.Layout = Application.SmartArtLayouts(1)

See also

Concepts

SmartArt Object

Other resources

SmartArt Object Members


SmartArt.Nodes Property (Office)

 Copy code hover
[image]

SmartArt.Nodes Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the children of the root node of the SmartArt diagram. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Nodes

expression An expression that returns a SmartArt object.

Remarks

The root node has no parent node and only contains children if there are children present in the SmartArt graphic's data model. In the following example, the nodes A and F will be returned.

  • A

    • B

      • C

    • D

      • E

  • F

Example

The following code adds a top level node in Microsoft PowerPoint.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.Nodes.Add

See also

Concepts

SmartArt Object

Other resources

SmartArt Object Members


SmartArt.Parent Property (Office)

 Copy code hover
[image]

SmartArt.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the calling object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Parent

expression An expression that returns a SmartArt object.

See also

Concepts

SmartArt Object

Other resources

SmartArt Object Members


SmartArt.QuickStyle Property (Office)

 Copy code hover
[image]

SmartArt.QuickStyle Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves or sets the SmartArt quick style applied to the SmartArt graphic. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .QuickStyle

expression An expression that returns a SmartArt object.

Example

The following code changes the quick style of Smart Art in Microsoft PowerPoint.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.QuickStyle = Application.SmartArtQuickStyles(i)

See also

Concepts

SmartArt Object

Other resources

SmartArt Object Members


SmartArt.Reverse Property (Office)

 Copy code hover
[image]

SmartArt.Reverse Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the state of the SmartArt diagram with regard to (left-to-right) LTR or (right-to-left) RTL, if the diagram supports reversal. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Reverse

expression An expression that returns a SmartArt object.

See also

Concepts

SmartArt Object

Other resources

SmartArt Object Members


SmartArt Methods (Office)

 Copy code hover
[image]

SmartArt Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Reset | Resets the SmartArt graphic to its original state.


SmartArt.Reset Method (Office)

 Copy code hover
[image]

SmartArt.Reset Method (Office)
See also Send feedback

Published: July 09, 2012

Resets the SmartArt graphic to its original state.

Version Information

Version Added: Office 2010

Syntax

expression .Reset

expression An expression that returns a SmartArt object.

Return Value

Nothing

Remarks

This action mirrors the functionality presented by the Reset Graphic button under the Design tab for SmartArt.

See also

Concepts

SmartArt Object

Other resources

SmartArt Object Members


SmartArtColor Object (Office)

 Copy code hover
[image]

SmartArtColor Object (Office)
See also Send feedback

Published: July 09, 2012

Chooses the color scheme for the SmartArt diagram.

Version Information

Version Added: Office 2010

Remarks

Simulates the commands on the Microsoft Office Fluent Ribbon user interface on the SmartArt Tools tab, on the Design group, on the Change Colors command.

Example

The following code sets the color scheme of the Smart Art diagram.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.Color = Application.SmartArtColors(1)

See also

Concepts

Object Model Reference

Other resources

SmartArtColor Object Members


SmartArtColor Members (Office)

 Copy code hover
[image]

SmartArtColor Members (Office)
Send feedback

Published: July 09, 2012

Chooses the color scheme for the SmartArt diagram.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtColor object. Read-only
Category | Retrieves the primary category name associated with the SmartArt color style. Read-only
Creator | Returns a 32-bit integer that indicates the application in which this object was created. Read-only
Description | Retrieves the description of the SmartArt color style. Read-only
Id | Retrieves the unique Id of the associated SmartArt color style. Read-only
Name | Retrieves the string name of the SmartArt color style. Read-only
Parent | Returns the calling object. Read-only


SmartArtColor Properties (Office)

 Copy code hover
[image]

SmartArtColor Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtColor object. Read-only
Category | Retrieves the primary category name associated with the SmartArt color style. Read-only
Creator | Returns a 32-bit integer that indicates the application in which this object was created. Read-only
Description | Retrieves the description of the SmartArt color style. Read-only
Id | Retrieves the unique Id of the associated SmartArt color style. Read-only
Name | Retrieves the string name of the SmartArt color style. Read-only
Parent | Returns the calling object. Read-only


SmartArtColor.Application Property (Office)

 Copy code hover
[image]

SmartArtColor.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SmartArtColor object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a SmartArtColor object.

See also

Concepts

SmartArtColor Object

Other resources

SmartArtColor Object Members


SmartArtColor.Category Property (Office)

 Copy code hover
[image]

SmartArtColor.Category Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the primary category name associated with the SmartArt color style. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Category

expression An expression that returns a SmartArtColor object.

See also

Concepts

SmartArtColor Object

Other resources

SmartArtColor Object Members


SmartArtColor.Creator Property (Office)

 Copy code hover
[image]

SmartArtColor.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Returns a 32-bit integer that indicates the application in which this object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a SmartArtColor object.

See also

Concepts

SmartArtColor Object

Other resources

SmartArtColor Object Members


SmartArtColor.Description Property (Office)

 Copy code hover
[image]

SmartArtColor.Description Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the description of the SmartArt color style. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Description

expression An expression that returns a SmartArtColor object.

See also

Concepts

SmartArtColor Object

Other resources

SmartArtColor Object Members


SmartArtColor.Id Property (Office)

 Copy code hover
[image]

SmartArtColor.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the unique Id of the associated SmartArt color style. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Id

expression An expression that returns a SmartArtColor object.

Remarks

The ID associated with this property is case sensitive.

See also

Concepts

SmartArtColor Object

Other resources

SmartArtColor Object Members


SmartArtColor.Name Property (Office)

 Copy code hover
[image]

SmartArtColor.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the string name of the SmartArt color style. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Name

expression An expression that returns a SmartArtColor object.

See also

Concepts

SmartArtColor Object

Other resources

SmartArtColor Object Members


SmartArtColor.Parent Property (Office)

 Copy code hover
[image]

SmartArtColor.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the calling object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Parent

expression An expression that returns a SmartArtColor object.

See also

Concepts

SmartArtColor Object

Other resources

SmartArtColor Object Members


SmartArtColors Object (Office)

 Copy code hover
[image]

SmartArtColors Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of SmartArt color styles.

Version Information

Version Added: Office 2010

Remarks

Simulates the commands on the Microsoft Office Fluent Ribbon user interface on the SmartArt Tools, on the Design group, on the Change Colors command.

Example

The following code sets the color scheme of the Smart Art diagram.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.Color = Application.SmartArtColors(1)

See also

Concepts

Object Model Reference

Other resources

SmartArtColors Object Members


SmartArtColors Members (Office)

 Copy code hover
[image]

SmartArtColors Members (Office)
Send feedback

Published: July 09, 2012

A collection of SmartArt color styles.

Methods

Name | Description
Item | Retrieves a SmartArtColor object at the specified index or with the specified unique Id.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtColors object. Read-only
Count | Retrieves the count of the number of SmartArtColor objects contained within the SmartArtColors collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtColors object was created. Read-only
Parent | Returns the calling object. Read-only


SmartArtColors Properties (Office)

 Copy code hover
[image]

SmartArtColors Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtColors object. Read-only
Count | Retrieves the count of the number of SmartArtColor objects contained within the SmartArtColors collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtColors object was created. Read-only
Parent | Returns the calling object. Read-only


SmartArtColors.Application Property (Office)

 Copy code hover
[image]

SmartArtColors.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SmartArtColors object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a SmartArtColors object.

See also

Concepts

SmartArtColors Object

Other resources

SmartArtColors Object Members


SmartArtColors.Count Property (Office)

 Copy code hover
[image]

SmartArtColors.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the count of the number of SmartArtColor objects contained within the SmartArtColors collection. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Count

expression An expression that returns a SmartArtColors object.

See also

Concepts

SmartArtColors Object

Other resources

SmartArtColors Object Members


SmartArtColors.Creator Property (Office)

 Copy code hover
[image]

SmartArtColors.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SmartArtColors object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a SmartArtColors object.

See also

Concepts

SmartArtColors Object

Other resources

SmartArtColors Object Members


SmartArtColors.Parent Property (Office)

 Copy code hover
[image]

SmartArtColors.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the calling object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Parent

expression An expression that returns a SmartArtColors object.

See also

Concepts

SmartArtColors Object

Other resources

SmartArtColors Object Members


SmartArtColors Methods (Office)

 Copy code hover
[image]

SmartArtColors Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Item | Retrieves a SmartArtColor object at the specified index or with the specified unique Id.


SmartArtColors.Item Method (Office)

 Copy code hover
[image]

SmartArtColors.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Retrieves a SmartArtColor object at the specified index or with the specified unique Id.

Version Information

Version Added: Office 2010

Syntax

expression .Item(Index)

expression An expression that returns a SmartArtColors object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | Specifies either an integer representing the index or a string representing the Id of the Smart Art color.

Return Value

SmartArtColor

See also

Concepts

SmartArtColors Object

Other resources

SmartArtColors Object Members


SmartArtLayout Object (Office)

 Copy code hover
[image]

SmartArtLayout Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a Smart Art diagram.

Version Information

Version Added: Office 2010

Remarks

Choices include Basic Block List, Picture Caption List, Vertical Bulleted List, etc.

Example

The following code changes the diagram style of a Smart Art diagram in Microsoft PowerPoint.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.Layout = Application.SmartArtLayouts(1)

See also

Concepts

Object Model Reference

Other resources

SmartArtLayout Object Members


SmartArtLayout Members (Office)

 Copy code hover
[image]

SmartArtLayout Members (Office)
Send feedback

Published: July 09, 2012

Represents a Smart Art diagram.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtLayout object. Read-only
Category | Retrieves the primary category name associated with the SmartArt layout. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtLayout object was created. Read-only
Description | Retrieves the description of the SmartArt layout. Read-only
Id | Retrieves the unique Id of the associated SmartArt layout. Read-only
Name | Retrieves the string name of the SmartArt layout. Read-only
Parent | Returns the calling object. Read-only


SmartArtLayout Properties (Office)

 Copy code hover
[image]

SmartArtLayout Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtLayout object. Read-only
Category | Retrieves the primary category name associated with the SmartArt layout. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtLayout object was created. Read-only
Description | Retrieves the description of the SmartArt layout. Read-only
Id | Retrieves the unique Id of the associated SmartArt layout. Read-only
Name | Retrieves the string name of the SmartArt layout. Read-only
Parent | Returns the calling object. Read-only


SmartArtLayout.Application Property (Office)

 Copy code hover
[image]

SmartArtLayout.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SmartArtLayout object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a SmartArtLayout object.

See also

Concepts

SmartArtLayout Object

Other resources

SmartArtLayout Object Members


SmartArtLayout.Category Property (Office)

 Copy code hover
[image]

SmartArtLayout.Category Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the primary category name associated with the SmartArt layout. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Category

expression An expression that returns a SmartArtLayout object.

See also

Concepts

SmartArtLayout Object

Other resources

SmartArtLayout Object Members


SmartArtLayout.Creator Property (Office)

 Copy code hover
[image]

SmartArtLayout.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SmartArtLayout object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a SmartArtLayout object.

See also

Concepts

SmartArtLayout Object

Other resources

SmartArtLayout Object Members


SmartArtLayout.Description Property (Office)

 Copy code hover
[image]

SmartArtLayout.Description Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the description of the SmartArt layout. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Description

expression An expression that returns a SmartArtLayout object.

See also

Concepts

SmartArtLayout Object

Other resources

SmartArtLayout Object Members


SmartArtLayout.Id Property (Office)

 Copy code hover
[image]

SmartArtLayout.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the unique Id of the associated SmartArt layout. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Id

expression An expression that returns a SmartArtLayout object.

Remarks

The ID associated with this property is case sensitive.

See also

Concepts

SmartArtLayout Object

Other resources

SmartArtLayout Object Members


SmartArtLayout.Name Property (Office)

 Copy code hover
[image]

SmartArtLayout.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the string name of the SmartArt layout. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Name

expression An expression that returns a SmartArtLayout object.

See also

Concepts

SmartArtLayout Object

Other resources

SmartArtLayout Object Members


SmartArtLayout.Parent Property (Office)

 Copy code hover
[image]

SmartArtLayout.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the calling object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Parent

expression An expression that returns a SmartArtLayout object.

See also

Concepts

SmartArtLayout Object

Other resources

SmartArtLayout Object Members


SmartArtLayouts Object (Office)

 Copy code hover
[image]

SmartArtLayouts Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of Smart Art layout diagrams.

Version Information

Version Added: Office 2010

Remarks

Choices include Basic Block List, Picture Caption List, Vertical Bulleted List, etc.

Example

The following code changes the diagram style of a Smart Art diagram in Microsoft PowerPoint.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.Layout = Application.SmartArtLayouts(1)

See also

Concepts

Object Model Reference

Other resources

SmartArtLayouts Object Members


SmartArtLayouts Members (Office)

 Copy code hover
[image]

SmartArtLayouts Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of Smart Art layout diagrams.

Methods

Name | Description
Item | Retrieves a SmartArtLayout object at the specified index or with the specified unique Id.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtLayouts object. Read-only
Count | Retrieves the count of the number of SmartArtLayout objects contained within the SmartArtLayouts collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtLayouts object was created. Read-only
Parent | Returns the calling object. Read-only


SmartArtLayouts Properties (Office)

 Copy code hover
[image]

SmartArtLayouts Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtLayouts object. Read-only
Count | Retrieves the count of the number of SmartArtLayout objects contained within the SmartArtLayouts collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtLayouts object was created. Read-only
Parent | Returns the calling object. Read-only


SmartArtLayouts.Application Property (Office)

 Copy code hover
[image]

SmartArtLayouts.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SmartArtLayouts object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a SmartArtLayouts object.

See also

Concepts

SmartArtLayouts Object

Other resources

SmartArtLayouts Object Members


SmartArtLayouts.Count Property (Office)

 Copy code hover
[image]

SmartArtLayouts.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the count of the number of SmartArtLayout objects contained within the SmartArtLayouts collection. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Count

expression An expression that returns a SmartArtLayouts object.

See also

Concepts

SmartArtLayouts Object

Other resources

SmartArtLayouts Object Members


SmartArtLayouts.Creator Property (Office)

 Copy code hover
[image]

SmartArtLayouts.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SmartArtLayouts object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a SmartArtLayouts object.

See also

Concepts

SmartArtLayouts Object

Other resources

SmartArtLayouts Object Members


SmartArtLayouts.Parent Property (Office)

 Copy code hover
[image]

SmartArtLayouts.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the calling object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Parent

expression An expression that returns a SmartArtLayouts object.

See also

Concepts

SmartArtLayouts Object

Other resources

SmartArtLayouts Object Members


SmartArtLayouts Methods (Office)

 Copy code hover
[image]

SmartArtLayouts Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Item | Retrieves a SmartArtLayout object at the specified index or with the specified unique Id.


SmartArtLayouts.Item Method (Office)

 Copy code hover
[image]

SmartArtLayouts.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Retrieves a SmartArtLayout object at the specified index or with the specified unique Id.

Version Information

Version Added: Office 2010

Syntax

expression .Item(Index)

expression An expression that returns a SmartArtLayouts object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | Specifies either an integer representing the index or a string representing the location of the SmartArtLayout object.

Return Value

SmartArtLayout

See also

Concepts

SmartArtLayouts Object

Other resources

SmartArtLayouts Object Members


SmartArtNode Object (Office)

 Copy code hover
[image]

SmartArtNode Object (Office)
See also Send feedback

Published: July 09, 2012

A single semantic node within the data model of a Smart Art graphic.

Version Information

Version Added: Office 2010

Example

The following code returns the number of nodes in the Smart Art diagram.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArtNodes.Count

See also

Concepts

Object Model Reference

Other resources

SmartArtNode Object Members


SmartArtNode Members (Office)

 Copy code hover
[image]

SmartArtNode Members (Office)
Send feedback

Published: July 09, 2012

A single semantic node within the data model of a Smart Art graphic.

Methods

Name | Description
AddNode | Adds a new SmartArtNode to the data model in the way specified by the SmartArtNodePosition value, and of type SmartArtNodeType.
Delete | Removes the current SmartArt node.
Demote | Demotes the current node a single level within the data model.
Larger | Increases the size of the SmartArt node. Mimics the behavior of the Larger button on the Microsoft Office Fluent Ribbon Format tab for SmartArt.
Promote | Promotes the current node (and all its children) a single level within the data model.
ReorderDown | Swaps a node with the next node in the bulleted list. This method reorder's the nodes entire family.
ReorderUp | Swaps a node with the previous node in the bulleted list. This method reorder's the nodes entire family.
Smaller | Decreases the size of the SmartArt. Mimics the behavior of the Smaller button on the Microsoft Office Fluent Ribbon UI Format tab for SmartArt.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtNode object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtNode object was created. Read-only
Hidden | Returns true if this node is a hidden node in the data model. Read-only
Level | Retrieves the node's level in the hierarchy. Read-only
Nodes | Retrieves the children nodes associated with this Smart Art Node. Read-only
OrgChartLayout | Retrieves or sets the MsoOrgChartLayoutType associated with this node if there is one. Read/write
Parent | Returns the calling object. Read-only
ParentNode | Retrieves the parent SmartArtNode of this SmartArtNode. Read-only
Shapes | Returns the shape range associated with this SmartArtNode object. Read-only
TextFrame2 | Returns the text associated with the SmartArtNode object. Read-only
Type | Retrieves the type of SmartArt node. Read-only


SmartArtNode Properties (Office)

 Copy code hover
[image]

SmartArtNode Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtNode object. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtNode object was created. Read-only
Hidden | Returns true if this node is a hidden node in the data model. Read-only
Level | Retrieves the node's level in the hierarchy. Read-only
Nodes | Retrieves the children nodes associated with this Smart Art Node. Read-only
OrgChartLayout | Retrieves or sets the MsoOrgChartLayoutType associated with this node if there is one. Read/write
Parent | Returns the calling object. Read-only
ParentNode | Retrieves the parent SmartArtNode of this SmartArtNode. Read-only
Shapes | Returns the shape range associated with this SmartArtNode object. Read-only
TextFrame2 | Returns the text associated with the SmartArtNode object. Read-only
Type | Retrieves the type of SmartArt node. Read-only


SmartArtNode.Application Property (Office)

 Copy code hover
[image]

SmartArtNode.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SmartArtNode object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a SmartArtNode object.

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Creator Property (Office)

 Copy code hover
[image]

SmartArtNode.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SmartArtNode object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a SmartArtNode object.

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Hidden Property (Office)

 Copy code hover
[image]

SmartArtNode.Hidden Property (Office)
See also Send feedback

Published: July 09, 2012

Returns true if this node is a hidden node in the data model. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Hidden

expression An expression that returns a SmartArtNode object.

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Level Property (Office)

 Copy code hover
[image]

SmartArtNode.Level Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the node's level in the hierarchy. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Level

expression An expression that returns a SmartArtNode object.

Remarks

The levels start at 1 and increment upward. If a node has no level, then a 0 is returned. For example, in the following data model, A and F have a level of 1, B and D have a level of 2, and C and E have a level of 3.

  • A

    • B

      • C

    • D

      • E

  • F

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Nodes Property (Office)

 Copy code hover
[image]

SmartArtNode.Nodes Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the children nodes associated with this Smart Art Node. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Nodes

expression An expression that returns a SmartArtNode object.

Example

The following code returns the number of nodes in the Smart Art diagram.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArtNodes.Nodes.Count

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.OrgChartLayout Property (Office)

 Copy code hover
[image]

SmartArtNode.OrgChartLayout Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves or sets the MsoOrgChartLayoutType associated with this node if there is one. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .OrgChartLayout

expression An expression that returns a SmartArtNode object.

Remarks

Possible members are:

  • msoOrgChartLayoutBothHanging

  • msoOrgChartLayoutDefault

  • msoOrgChartLayoutLeftHanging

  • msoOrgChartLayoutMixed

  • msoOrgChartLayoutRightHanging

  • msoOrgChartLayoutStandard

Example

The following code sets the OrgChartLayout property to the default layout.

VBA Copy code Copy code
Dim saNode As SmartArtNode
saNode.OrgChartLayout = msoOrgChartLayoutDefault

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Parent Property (Office)

 Copy code hover
[image]

SmartArtNode.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the calling object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Parent

expression An expression that returns a SmartArtNode object.

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.ParentNode Property (Office)

 Copy code hover
[image]

SmartArtNode.ParentNode Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the parent SmartArtNode of this SmartArtNode. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .ParentNode

expression An expression that returns a SmartArtNode object.

Remarks

If this node is the root node, an error is returned.

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Shapes Property (Office)

 Copy code hover
[image]

SmartArtNode.Shapes Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the shape range associated with this SmartArtNode object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Shapes

expression An expression that returns a SmartArtNode object.

Remarks

To find the range, use the Count property.

Example

The following code returns the shape range.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArtNodes.Item(1).Shapes.Count.

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.TextFrame2 Property (Office)

 Copy code hover
[image]

SmartArtNode.TextFrame2 Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the text associated with the SmartArtNode object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .TextFrame2

expression An expression that returns a SmartArtNode object.

Example

The following example sets the text inside the first node.

VBA Copy code Copy code
smartart.AllNodes(1).TextFrame2.TextRange.Text="Node 1"

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Type Property (Office)

 Copy code hover
[image]

SmartArtNode.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the type of SmartArt node. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Type

expression An expression that returns a SmartArtNode object.

Remarks

Possible values are msoSmartArtNodeTypeAssistant or msoSmartArtNodeTypeDefault.

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode Methods (Office)

 Copy code hover
[image]

SmartArtNode Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
AddNode | Adds a new SmartArtNode to the data model in the way specified by the SmartArtNodePosition value, and of type SmartArtNodeType.
Delete | Removes the current SmartArt node.
Demote | Demotes the current node a single level within the data model.
Larger | Increases the size of the SmartArt node. Mimics the behavior of the Larger button on the Microsoft Office Fluent Ribbon Format tab for SmartArt.
Promote | Promotes the current node (and all its children) a single level within the data model.
ReorderDown | Swaps a node with the next node in the bulleted list. This method reorder's the nodes entire family.
ReorderUp | Swaps a node with the previous node in the bulleted list. This method reorder's the nodes entire family.
Smaller | Decreases the size of the SmartArt. Mimics the behavior of the Smaller button on the Microsoft Office Fluent Ribbon UI Format tab for SmartArt.


SmartArtNode.AddNode Method (Office)

 Copy code hover
[image]

SmartArtNode.AddNode Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a new SmartArtNode to the data model in the way specified by the SmartArtNodePosition value, and of type SmartArtNodeType.

Version Information

Version Added: Office 2010

Syntax

expression .AddNode(Position, Type)

expression An expression that returns a SmartArtNode object.

Parameters

Name | Required/Optional | Data Type | Description
Position | Optional | MsoSmartArtNodePosition | Specifies the location of the SmartArtNode in the data model. For example, msoSmartArtNodeAbove or msoSmartArtNodeAfter.
Type | Optional | MsoSmartArtNodeType | Specifies the type of the added SmartArtNode. For example, msoSmartArtNodeTypeAssistant or msoSmartArtNodeTypeDefault.

Return Value

SmartArtNode

Example

The following code adds a default SmartArtNode below the current node.

VBA Copy code Copy code
Dim saNode As SmartArtNode

saNode = saNode.AddNode(msoSmartArtNodeBelow, msoSmartArtNodeTypeDefault)

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Delete Method (Office)

 Copy code hover
[image]

SmartArtNode.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Removes the current SmartArt node.

Version Information

Version Added: Office 2010

Syntax

expression .Delete

expression An expression that returns a SmartArtNode object.

Return Value

Nothing

Remarks

When the node is deleted, the first child gets promoted. In the following data model: if B is deleted, the data model then looks like the following:

  • A

    • B

      • C

  • D

  • A

    • C

  • D

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Demote Method (Office)

 Copy code hover
[image]

SmartArtNode.Demote Method (Office)
See also Send feedback

Published: July 09, 2012

Demotes the current node a single level within the data model.

Version Information

Version Added: Office 2010

Syntax

expression .Demote

expression An expression that returns a SmartArtNode object.

Return Value

Nothing

Remarks

This functionality mimics the Demote button in the Microsoft Office Fluent Ribbon UI when working within the content pane. For example, given the following data model: if B is demoted, the resulting data model looks like the following:

  • A

  • B

    • C

  • D

  • A

    • B

    • C

  • D

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Larger Method (Office)

 Copy code hover
[image]

SmartArtNode.Larger Method (Office)
See also Send feedback

Published: July 09, 2012

Increases the size of the SmartArt node. Mimics the behavior of the Larger button on the Microsoft Office Fluent Ribbon Format tab for SmartArt.

Version Information

Version Added: Office 2010

Syntax

expression .Larger

expression An expression that returns a SmartArtNode object.

Return Value

Nothing

Remarks

The actual amount of increase depends on the layout of the nodes.

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Promote Method (Office)

 Copy code hover
[image]

SmartArtNode.Promote Method (Office)
See also Send feedback

Published: July 09, 2012

Promotes the current node (and all its children) a single level within the data model.

Version Information

Version Added: Office 2010

Syntax

expression .Promote

expression An expression that returns a SmartArtNode object.

Return Value

Nothing

Remarks

This functionality mimics the promote button on the Microsoft Office Fluent Ribbon UI when working within the content pane. For example, given the following data model: if B is promoted, the resulting data model looks like the following:

  • A

    • B

      • C

  • D

  • A

  • B

    • C

  • D

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.ReorderDown Method (Office)

 Copy code hover
[image]

SmartArtNode.ReorderDown Method (Office)
See also Send feedback

Published: July 09, 2012

Swaps a node with the next node in the bulleted list. This method reorder's the nodes entire family.

Version Information

Version Added: Office 2010

Syntax

expression .ReorderDown

expression An expression that returns a SmartArtNode object.

Return Value

Nothing

Remarks

This method simulates clicking the Reorder Down buttons on the Microsoft Office Fluent Ribbon user interface which is located on the SmartArt Tools tab, on the Design group on Reorder Down.

Example

The following code swaps the first node with the next node and reorders all of its descendants.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.Nodes(1).ReorderDown

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.ReorderUp Method (Office)

 Copy code hover
[image]

SmartArtNode.ReorderUp Method (Office)
See also Send feedback

Published: July 09, 2012

Swaps a node with the previous node in the bulleted list. This method reorder's the nodes entire family.

Version Information

Version Added: Office 2010

Syntax

expression .ReorderUp

expression An expression that returns a SmartArtNode object.

Return Value

Nothing

Remarks

This method simulates clicking the Reorder Up button on the Microsoft Office Fluent Ribbon user interface which is located on the SmartArt Tools tab, on the Design group on Reorder Up.

Example

The following code swaps the first node with the next node and reorders the nodes parents.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.Nodes(2).ReorderUp

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNode.Smaller Method (Office)

 Copy code hover
[image]

SmartArtNode.Smaller Method (Office)
See also Send feedback

Published: July 09, 2012

Decreases the size of the SmartArt. Mimics the behavior of the Smaller button on the Microsoft Office Fluent Ribbon UI Format tab for SmartArt.

Version Information

Version Added: Office 2010

Syntax

expression .Smaller

expression An expression that returns a SmartArtNode object.

Return Value

Nothing

Remarks

The amount of decrease depends on the layout size of the node.

See also

Concepts

SmartArtNode Object

Other resources

SmartArtNode Object Members


SmartArtNodes Object (Office)

 Copy code hover
[image]

SmartArtNodes Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of nodes within a Smart Art diagram.

Version Information

Version Added: Office 2010

Remarks

These nodes correspond directly to semantic elements contained within the data model of the graphic.

Example

The following code returns the number of nodes in the Smart Art diagram.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArtNodes.Count

See also

Concepts

Object Model Reference

Other resources

SmartArtNodes Object Members


SmartArtNodes Members (Office)

 Copy code hover
[image]

SmartArtNodes Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of nodes within a Smart Art diagram.

Methods

Name | Description
Add | Adds a new SmartArtNode object to the diagram with specified text.
Item | Retrieves a SmartArtNode object at the specified index or with the specified unique Id.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtNodes object. Read-only
Count | Retrieves the number of SmartArtNode objects contained within the SmartArtNodes collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtNodes object was created. Read-only
Parent | Returns the calling object. Read-only


SmartArtNodes Properties (Office)

 Copy code hover
[image]

SmartArtNodes Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtNodes object. Read-only
Count | Retrieves the number of SmartArtNode objects contained within the SmartArtNodes collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtNodes object was created. Read-only
Parent | Returns the calling object. Read-only


SmartArtNodes.Application Property (Office)

 Copy code hover
[image]

SmartArtNodes.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SmartArtNodes object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a SmartArtNodes object.

See also

Concepts

SmartArtNodes Object

Other resources

SmartArtNodes Object Members


SmartArtNodes.Count Property (Office)

 Copy code hover
[image]

SmartArtNodes.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the number of SmartArtNode objects contained within the SmartArtNodes collection. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Count

expression An expression that returns a SmartArtNodes object.

See also

Concepts

SmartArtNodes Object

Other resources

SmartArtNodes Object Members


SmartArtNodes.Creator Property (Office)

 Copy code hover
[image]

SmartArtNodes.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SmartArtNodes object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a SmartArtNodes object.

See also

Concepts

SmartArtNodes Object

Other resources

SmartArtNodes Object Members


SmartArtNodes.Parent Property (Office)

 Copy code hover
[image]

SmartArtNodes.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the calling object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Parent

expression An expression that returns a SmartArtNodes object.

See also

Concepts

SmartArtNodes Object

Other resources

SmartArtNodes Object Members


SmartArtNodes Methods (Office)

 Copy code hover
[image]

SmartArtNodes Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a new SmartArtNode object to the diagram with specified text.
Item | Retrieves a SmartArtNode object at the specified index or with the specified unique Id.


SmartArtNodes.Add Method (Office)

 Copy code hover
[image]

SmartArtNodes.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a new SmartArtNode object to the diagram with specified text.

Version Information

Version Added: Office 2010

Syntax

expression .Add

expression An expression that returns a SmartArtNodes object.

Return Value

SmartArtNode

Remarks

This new node is added to the bottom of the data model at the top most level for this collection of nodes. If the highest level was 2, then the new node's level would then be 2 as well.

Example

The following code adds a SmartArtNode to the collection of SmartArtNodes.

VBA Copy code Copy code
Dim saNodes As SmartArtNodes
saNodes.Add()

See also

Concepts

SmartArtNodes Object

Other resources

SmartArtNodes Object Members


SmartArtNodes.Item Method (Office)

 Copy code hover
[image]

SmartArtNodes.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Retrieves a SmartArtNode object at the specified index or with the specified unique Id.

Version Information

Version Added: Office 2010

Syntax

expression .Item(Index)

expression An expression that returns a SmartArtNodes object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | Specifies either an integer representing the index or a string representing the location of the SmartArtNode object.

Return Value

SmartArtNode

See also

Concepts

SmartArtNodes Object

Other resources

SmartArtNodes Object Members


SmartArtQuickStyle Object (Office)

 Copy code hover
[image]

SmartArtQuickStyle Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a Smart Art quick style

Version Information

Version Added: Office 2010

Example

The following code changes the quick style of a Smart Art diagram in Microsoft PowerPoint.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.QuickStyle = Application.SmartArtQuickStyles(i)

See also

Concepts

Object Model Reference

Other resources

SmartArtQuickStyle Object Members


SmartArtQuickStyle Members (Office)

 Copy code hover
[image]

SmartArtQuickStyle Members (Office)
Send feedback

Published: July 09, 2012

Represents a Smart Art quick style

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtQuickStyle object. Read-only
Category | Retrieves the primary category name associated with the SmartArt quick style. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtQuickStyle object was created. Read-only
Description | Retrieves the description of the SmartArt quick style. Read-only
Id | Retrieves the unique Id of the associated SmartArt quick style. Read-only
Name | Retrieves the string name of the SmartArt quick style. Read-only
Parent | Returns the calling object. Read-only


SmartArtQuickStyle Properties (Office)

 Copy code hover
[image]

SmartArtQuickStyle Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtQuickStyle object. Read-only
Category | Retrieves the primary category name associated with the SmartArt quick style. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtQuickStyle object was created. Read-only
Description | Retrieves the description of the SmartArt quick style. Read-only
Id | Retrieves the unique Id of the associated SmartArt quick style. Read-only
Name | Retrieves the string name of the SmartArt quick style. Read-only
Parent | Returns the calling object. Read-only


SmartArtQuickStyle.Application Property (Office)

 Copy code hover
[image]

SmartArtQuickStyle.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SmartArtQuickStyle object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a SmartArtQuickStyle object.

See also

Concepts

SmartArtQuickStyle Object

Other resources

SmartArtQuickStyle Object Members


SmartArtQuickStyle.Category Property (Office)

 Copy code hover
[image]

SmartArtQuickStyle.Category Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the primary category name associated with the SmartArt quick style. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Category

expression An expression that returns a SmartArtQuickStyle object.

See also

Concepts

SmartArtQuickStyle Object

Other resources

SmartArtQuickStyle Object Members


SmartArtQuickStyle.Creator Property (Office)

 Copy code hover
[image]

SmartArtQuickStyle.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SmartArtQuickStyle object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a SmartArtQuickStyle object.

See also

Concepts

SmartArtQuickStyle Object

Other resources

SmartArtQuickStyle Object Members


SmartArtQuickStyle.Description Property (Office)

 Copy code hover
[image]

SmartArtQuickStyle.Description Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the description of the SmartArt quick style. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Description

expression An expression that returns a SmartArtQuickStyle object.

See also

Concepts

SmartArtQuickStyle Object

Other resources

SmartArtQuickStyle Object Members


SmartArtQuickStyle.Id Property (Office)

 Copy code hover
[image]

SmartArtQuickStyle.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the unique Id of the associated SmartArt quick style. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Id

expression An expression that returns a SmartArtQuickStyle object.

Remarks

The ID associated with this property is case sensitive.

See also

Concepts

SmartArtQuickStyle Object

Other resources

SmartArtQuickStyle Object Members


SmartArtQuickStyle.Name Property (Office)

 Copy code hover
[image]

SmartArtQuickStyle.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the string name of the SmartArt quick style. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Name

expression An expression that returns a SmartArtQuickStyle object.

See also

Concepts

SmartArtQuickStyle Object

Other resources

SmartArtQuickStyle Object Members


SmartArtQuickStyle.Parent Property (Office)

 Copy code hover
[image]

SmartArtQuickStyle.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the calling object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Parent

expression An expression that returns a SmartArtQuickStyle object.

See also

Concepts

SmartArtQuickStyle Object

Other resources

SmartArtQuickStyle Object Members


SmartArtQuickStyles Object (Office)

 Copy code hover
[image]

SmartArtQuickStyles Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of Smart Art quick styles.

Version Information

Version Added: Office 2010

Example

The following code changes the quick style of a Smart Art diagram in Microsoft PowerPoint.

VBA Copy code Copy code
ActivePresentation.Slides(1).Shapes(1).SmartArt.QuickStyle = Application.SmartArtQuickStyles(i)

See also

Concepts

Object Model Reference

Other resources

SmartArtQuickStyles Object Members


SmartArtQuickStyles Members (Office)

 Copy code hover
[image]

SmartArtQuickStyles Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of Smart Art quick styles.

Methods

Name | Description
Item | Retrieves a SmartArtQuickStyle object at the specified index or with the specified unique Id.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtQuickStyles object. Read-only
Count | Retrieves the count of the number of SmartArtQuickStyle objects contained within the SmartArtQuickStyles collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtQuickStyles object was created. Read-only
Parent | Returns the calling object. Read-only


SmartArtQuickStyles Properties (Office)

 Copy code hover
[image]

SmartArtQuickStyles Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartArtQuickStyles object. Read-only
Count | Retrieves the count of the number of SmartArtQuickStyle objects contained within the SmartArtQuickStyles collection. Read-only
Creator | Gets a 32-bit integer that indicates the application in which the SmartArtQuickStyles object was created. Read-only
Parent | Returns the calling object. Read-only


SmartArtQuickStyles.Application Property (Office)

 Copy code hover
[image]

SmartArtQuickStyles.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SmartArtQuickStyles object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a SmartArtQuickStyles object.

See also

Concepts

SmartArtQuickStyles Object

Other resources

SmartArtQuickStyles Object Members


SmartArtQuickStyles.Count Property (Office)

 Copy code hover
[image]

SmartArtQuickStyles.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Retrieves the count of the number of SmartArtQuickStyle objects contained within the SmartArtQuickStyles collection. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Count

expression An expression that returns a SmartArtQuickStyles object.

See also

Concepts

SmartArtQuickStyles Object

Other resources

SmartArtQuickStyles Object Members


SmartArtQuickStyles.Creator Property (Office)

 Copy code hover
[image]

SmartArtQuickStyles.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SmartArtQuickStyles object was created. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a SmartArtQuickStyles object.

See also

Concepts

SmartArtQuickStyles Object

Other resources

SmartArtQuickStyles Object Members


SmartArtQuickStyles.Parent Property (Office)

 Copy code hover
[image]

SmartArtQuickStyles.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the calling object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Parent

expression An expression that returns a SmartArtQuickStyles object.

See also

Concepts

SmartArtQuickStyles Object

Other resources

SmartArtQuickStyles Object Members


SmartArtQuickStyles Methods (Office)

 Copy code hover
[image]

SmartArtQuickStyles Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Item | Retrieves a SmartArtQuickStyle object at the specified index or with the specified unique Id.


SmartArtQuickStyles.Item Method (Office)

 Copy code hover
[image]

SmartArtQuickStyles.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Retrieves a SmartArtQuickStyle object at the specified index or with the specified unique Id.

Version Information

Version Added: Office 2010

Syntax

expression .Item(Index)

expression An expression that returns a SmartArtQuickStyles object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | Specifies either an integer representing the index or a string representing the location of the SmartArtQuickStyle object.

Return Value

SmartArtQuickStyle

See also

Concepts

SmartArtQuickStyles Object

Other resources

SmartArtQuickStyles Object Members


SmartDocument Object (Office)

 Copy code hover
[image]

SmartDocument Object (Office)
See also Send feedback

Published: July 09, 2012

The SmartDocument property of the Document object in Microsoft Word and the Workbook object in Microsoft Excel returns a SmartDocument object.

Remarks

Use the SmartDocument object to manage the XML expansion pack attached to the active document.

Use the SmartDocument object's SolutionID and SolutionURI properties to retrieve information about the XML expansion pack attached to the active document or workbook. Use the PickSolution method to allow the user to select an available XML expansion pack from a list to attach to the active document or workbook. Use the RefreshPane method to refresh the smart document's Document Actions task pane.

The SmartDocument object model is available whether or not a document has an XML expansion pack attached. The SmartDocument property of the Document or Workbook objects does not return Nothing when the active document has no XML expansion pack attached. Examine the SolutionID property to determine whether the active document has an XML expansion pack attached.

See also

Concepts

Object Model Reference

Other resources

SmartDocument Object Members


SmartDocument Members (Office)

 Copy code hover
[image]

SmartDocument Members (Office)
Send feedback

Published: July 09, 2012

The SmartDocument property of the Document object in Microsoft Word and the Workbook object in Microsoft Excel returns a SmartDocument object.

Methods

Name | Description
PickSolution | Displays a dialog box that allows the user to choose an available XML expansion pack to attach to the active document in Microsoft Word or a workbook in Microsoft Excel.
RefreshPane | Refreshes the Document Actions task pane for the active document in Microsoft Word or a workbook in Microsoft Excel.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartDocument object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SmartDocument object was created. Read-only.
SolutionID | Gets or sets the ID, often a globally unique identifier (GUID), which identifies the XML expansion pack attached to the active document in Microsoft Word or workbook in Microsoft Excel. Read/write.
SolutionURL | Gets or sets an absolute URL which provides the complete path to the XML expansion pack file attached to the active document in Microsoft Word or a workbook in Microsoft Excel. Read/write.


SmartDocument Properties (Office)

 Copy code hover
[image]

SmartDocument Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SmartDocument object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SmartDocument object was created. Read-only.
SolutionID | Gets or sets the ID, often a globally unique identifier (GUID), which identifies the XML expansion pack attached to the active document in Microsoft Word or workbook in Microsoft Excel. Read/write.
SolutionURL | Gets or sets an absolute URL which provides the complete path to the XML expansion pack file attached to the active document in Microsoft Word or a workbook in Microsoft Excel. Read/write.


SmartDocument.Application Property (Office)

 Copy code hover
[image]

SmartDocument.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SmartDocument object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a SmartDocument object.

Return Value

Object

See also

Concepts

SmartDocument Object

Other resources

SmartDocument Object Members


SmartDocument.Creator Property (Office)

 Copy code hover
[image]

SmartDocument.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SmartDocument object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a SmartDocument object.

Return Value

Long

See also

Concepts

SmartDocument Object

Other resources

SmartDocument Object Members


SmartDocument.SolutionID Property (Office)

 Copy code hover
[image]

SmartDocument.SolutionID Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the ID, often a globally unique identifier (GUID), which identifies the XML expansion pack attached to the active document in Microsoft Word or workbook in Microsoft Excel. Read/write.

Syntax

expression .SolutionID

expression A variable that represents a SmartDocument object.

Remarks

The SolutionID property returns an empty string or "None" when no XML expansion pack is attached to the active document.

Provide appropriate values for the SolutionID and SolutionURL properties to attach an available XML expansion pack to the active document to transform it into a smart document without using the PickSolution method. Set the SolutionID and SolutionUrl properties to empty strings to remove the attached XML expansion pack.

Example

The following example determines whether an XML expansion pack is attached to the active Excel workbook by checking the SolutionID property.

Copy code Copy code
 Dim objSmartDoc As Office.SmartDocument
 Set objSmartDoc = ActiveWorkbook.SmartDocument
 If objSmartDoc.SolutionID = "None" Or objSmartDoc.SolutionID = "" Then
 MsgBox "No XML expansion pack attached."
 Else
 MsgBox "Smart document Solution ID: " & _
 objSmartDoc.SolutionID
 End If
 Set objSmartDoc = Nothing

See also

Concepts

SmartDocument Object

Other resources

SmartDocument Object Members


SmartDocument.SolutionURL Property (Office)

 Copy code hover
[image]

SmartDocument.SolutionURL Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets an absolute URL which provides the complete path to the XML expansion pack file attached to the active document in Microsoft Word or a workbook in Microsoft Excel. Read/write.

Syntax

expression .SolutionURL

expression A variable that represents a SmartDocument object.

Remarks

The SolutionUrl property returns an empty string when no XML expansion pack is attached to the active document.

Provide appropriate values for the SolutionID and SolutionUrl properties to attach an available XML expansion pack to the active document and transform it into a smart document without using the PickSolution method. Set the SolutionID and SolutionUrl properties to empty strings to remove the attached XML expansion pack

Example

The following example determines whether an XML expansion pack is attached to the active Word document, then displays the smart document's Solution URL.

Copy code Copy code
 Dim objSmartDoc As Office.SmartDocument
 Set objSmartDoc = ActiveDocument.SmartDocument
 If objSmartDoc.SolutionID = "None" Or objSmartDoc.SolutionID = "" Then
 MsgBox "No XML expansion pack attached."
 Else
 MsgBox "Smart document Solution URL: " & _
 objSmartDoc.SolutionURL
 End If
 Set objSmartDoc = Nothing

See also

Concepts

SmartDocument Object

Other resources

SmartDocument Object Members


SmartDocument Methods (Office)

 Copy code hover
[image]

SmartDocument Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
PickSolution | Displays a dialog box that allows the user to choose an available XML expansion pack to attach to the active document in Microsoft Word or a workbook in Microsoft Excel.
RefreshPane | Refreshes the Document Actions task pane for the active document in Microsoft Word or a workbook in Microsoft Excel.


SmartDocument.PickSolution Method (Office)

 Copy code hover
[image]

SmartDocument.PickSolution Method (Office)
See also Send feedback

Published: July 09, 2012

Displays a dialog box that allows the user to choose an available XML expansion pack to attach to the active document in Microsoft Word or a workbook in Microsoft Excel.

Syntax

expression .PickSolution(ConsiderAllSchemas)

expression A variable that represents a SmartDocument object.

Parameters

Name | Required/Optional | Data Type | Description
ConsiderAllSchemas | Optional | Boolean | True displays all available XML expansion packs installed on the user's computer. False displays only XML expansion packs applicable to the active document. Default value is False.

Remarks

Use the PickSolution method to allow the user to select an XML expansion pack from a list. The schema attached to the active document or workbook determines which XML expansion packs are applicable.

The PickSolution method does not return a value to indicate whether the user selected an XML expansion pack or clicked Cancel in the dialog box. Check the SolutionID property after calling PickSolution to determine whether an XML expansion pack has been attached.

If the smart document developer has failed to specify "targetApplication" in the XML expansion pack manifest file, the list displayed by PickSolution may include XML expansion packs that are not targeted to the active application; for example, an Excel user may see XML expansion packs targeted exclusively to Word. In these circumstances, the user may select an XML expansion pack that is not appropriate for the active application.

For more information on smart documents or XML expansion packs for smart documents, please see the Smart Document Software Development Kit (SDK) on the Microsoft Developer Network (MSDN) Web site.

Example

The following example checks the SolutionID property to determine whether the active Microsoft Word document already has an attached XML expansion pack; if not, it displays a dialog box which allows the user to choose an available XML expansion pack. It then displays the properties of the smart document.

Copy code Copy code
 Dim objSmartDoc As Office.SmartDocument
 Dim strSmartDocInfo As String
 Set objSmartDoc = ActiveDocument.SmartDocument
 If objSmartDoc.SolutionID = "None" Or objSmartDoc.SolutionID = "" Then
 objSmartDoc.PickSolution True
 End If
 If objSmartDoc.SolutionID > "None" And objSmartDoc.SolutionID > "" Then
 strSmartDocInfo = "SolutionID: " & objSmartDoc.SolutionID & vbCrLf & _
 "SolutionURL: " & objSmartDoc.SolutionURL
 MsgBox strSmartDocInfo, vbInformation + vbOKOnly, "Smart Doc Properties"
 Else
 MsgBox "The user clicked Cancel."
 End If
 Set objSmartDoc = Nothing

See also

Concepts

SmartDocument Object

Other resources

SmartDocument Object Members


SmartDocument.RefreshPane Method (Office)

 Copy code hover
[image]

SmartDocument.RefreshPane Method (Office)
See also Send feedback

Published: July 09, 2012

Refreshes the Document Actions task pane for the active document in Microsoft Word or a workbook in Microsoft Excel.

Syntax

expression .RefreshPane

expression A variable that represents a SmartDocument object.

Remarks

The RefreshPane method raises an error if the active document does not have an XML expansion pack attached.

Example

The following example determines whether the active Excel workbook has an XML expansion pack attached. If so, it refreshes the smart document's Document Actions task pane.

Copy code Copy code
 Dim objSmartDoc As Office.SmartDocument
 Set objSmartDoc = ActiveWorkbook.SmartDocument
 If objSmartDoc.SolutionID > "None" Then
 objSmartDoc.RefreshPane
 Else
 MsgBox "No XML expansion pack attached."
 End If

See also

Concepts

SmartDocument Object

Other resources

SmartDocument Object Members


SoftEdgeFormat Object (Office)

 Copy code hover
[image]

SoftEdgeFormat Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the soft edges effect in Office graphics.

Remarks

The Soft Edge effect creates a mask around the edge of an object and blends the object with the transparent edge. The result is a faded or "feathered"edge.

Example

This example sets the soft edge formatting for the text for the second shape on the second slide in a PowerPoint presentation:

VBA Copy code Copy code
With ActivePresentation.Slides(1).Shapes(2)
 With .Text.Font
 .Size = 32
 .Name = "Palatino"
 .Softedgeformat = msosoftedge6
 End With
End With

See also

Concepts

Object Model Reference

Other resources

SoftEdgeFormat Object Members


SoftEdgeFormat Members (Office)

 Copy code hover
[image]

SoftEdgeFormat Members (Office)
Send feedback

Published: July 09, 2012

Represents the soft edges effect in Office graphics.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SoftEdgeFormat object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SoftEdgeFormat object was created. Read-only.
Radius | Gets or sets the size, measured in points, of the soft edge effect of the shape. Read/write
Type | Gets or sets the type of the SoftEdgeFormat object. Read/write.


SoftEdgeFormat Properties (Office)

 Copy code hover
[image]

SoftEdgeFormat Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the SoftEdgeFormat object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the SoftEdgeFormat object was created. Read-only.
Radius | Gets or sets the size, measured in points, of the soft edge effect of the shape. Read/write
Type | Gets or sets the type of the SoftEdgeFormat object. Read/write.


SoftEdgeFormat.Application Property (Office)

 Copy code hover
[image]

SoftEdgeFormat.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the SoftEdgeFormat object. Read-only.

Syntax

expression .Application

expression An expression that returns a SoftEdgeFormat object.

Return Value

Object

See also

Concepts

SoftEdgeFormat Object

Other resources

SoftEdgeFormat Object Members


SoftEdgeFormat.Creator Property (Office)

 Copy code hover
[image]

SoftEdgeFormat.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the SoftEdgeFormat object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a SoftEdgeFormat object.

Return Value

Long

See also

Concepts

SoftEdgeFormat Object

Other resources

SoftEdgeFormat Object Members


SoftEdgeFormat.Radius Property (Office)

 Copy code hover
[image]

SoftEdgeFormat.Radius Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the size, measured in points, of the soft edge effect of the shape. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Radius

expression An expression that returns a SoftEdgeFormat object.

See also

Concepts

SoftEdgeFormat Object

Other resources

SoftEdgeFormat Object Members


SoftEdgeFormat.Type Property (Office)

 Copy code hover
[image]

SoftEdgeFormat.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the type of the SoftEdgeFormat object. Read/write.

Syntax

expression .Type

expression An expression that returns a SoftEdgeFormat object.

Return Value

MsoSoftEdgeType

See also

Concepts

SoftEdgeFormat Object

Other resources

SoftEdgeFormat Object Members


Sync Object (Office)

 Copy code hover
[image]

Sync Object (Office)
See also Send feedback

Published: July 09, 2012

The Sync property of the Document object in Microsoft Word, the Workbook object in Microsoft Excel, and the Presentation object in Microsoft PowerPoint returns a Sync object.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Remarks

Use the Sync object to manage the synchronization of the local and server copies of a shared document stored in a SharePoint site. The Status property returns important information about the current state of synchronization. Use the GetUpdate method to refresh the sync status. Use the LastSyncTime, ErrorType, and WorkspaceLastChangedBy properties to return additional information.

See the Status property for additional information on the differences and conflicts that can exist between the local and server copies of shared documents.

Use the PutUpdate method to save local changes to the server. Close and re-open the document to retrieve the latest version from the server when no local changes have been made. Use the ResolveConflict method to resolve differences between the local and the server copies, or the OpenVersion method to open a different version alongside the currently open local version of the document.

The GetUpdate, PutUpdate, and ResolveConflict methods of the Sync object do not return status codes because they complete their tasks asynchronously. The Sync object provides important status information through a single event, which the developer can access through the following application-specific events:

  • in Word, through the Sync event of the Document object or the DocumentSync event of the Application object;

  • in Excel, through the Sync event of the Workbook object or the WorkbookSync event of the Application object;

  • in Microsoft PowerPoint, through the PresentationSync event of the Application object.

The Sync event described above returns an msoSyncEventType value.

The Sync object model is available whether sharing and synchronization are enabled or disabled on the active document. The Sync property of the Document, Workbook, and Presentation objects does not return Nothing when the active document is not shared or synchronization is not enabled. Use the Status property to determine whether the document is shared and whether synchronization is enabled.

Not all document synchronization problems raise trappable run-time errors. After using the methods of the Sync object, it's a good idea to check the Status property; if the Status property is msoSyncStatusError, check the ErrorType property for additional information on the type of error that has occurred.

In many circumstances, the best way to resolve an error condition is to call the GetUpdate method. For example, if a call to PutUpdate results in an error condition, then a call to GetUpdate will reset the status to msoSyncStatusLocalChanges.

Example

The following example demonstrates various methods of the Sync object based on the status of the active document.

VBA Copy code Copy code
Dim objSync As Office.Sync
    Dim strStatus As String
    Set objSync = ActiveDocument.Sync
    If objSync.Status > msoSyncStatusNoSharedWorkspace Then
        Select Case objSync.Status
            Case msoSyncStatusConflict
                objSync.ResolveConflict msoSyncConflictMerge
                ActiveDocument.Save
                objSync.ResolveConflict msoSyncConflictClientWins
                strStatus = "Conflict resolved by merging changes."
            Case msoSyncStatusError
                strStatus = "Last error type: " & objSync.ErrorType
            Case msoSyncStatusLatest
                strStatus = "Document copies already in sync."
            Case msoSyncStatusLocalChanges
                objSync.PutUpdate
                strStatus = "Local changes saved to server."
            Case msoSyncStatusNewerAvailable
                objSync.GetUpdate
                strStatus = "Local copy updated from server."
            Case msoSyncStatusSuspended
                objSync.Unsuspend
                strStatus = "Synchronization resumed."
        End Select
    Else
        strStatus = "Not a shared workspace document."
    End If
    MsgBox strStatus, vbInformation + vbOKOnly, "Sync Information"
    Set objSync = Nothing

See also

Concepts

Object Model Reference

Other resources

Sync Object Members


Sync Members (Office)

 Copy code hover
[image]

Sync Members (Office)
Send feedback

Published: July 09, 2012

The Sync property of the Document object in Microsoft Word, the Workbook object in Microsoft Excel, and the Presentation object in Microsoft PowerPoint returns a Sync object.

Methods

Name | Description
GetUpdate | Compares the local version of the shared document to the version on the server.
OpenVersion | Opens a different version of the shared document alongside the currently open local version.
PutUpdate | Updates the server copy of the shared document with the local copy.
ResolveConflict | Resolves conflicts between the local and the server copies of a shared document.
Unsuspend | Resumes synchronization between the local copy and the server copy of a shared document.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the Sync object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the Sync object was created. Read-only.
ErrorType | Gets a MsoSyncErrorType constant which indicates the type of the most recent document synchronization error. Read-only.
LastSyncTime | Gets the date and time when the local copy of the active document was last synchronized with the server copy. Read-only.
Parent | Gets the Parent object for the Sync object. Read-only.
Status | Gets the status of the synchronization of the local copy of the active document with the server copy. Read-only.
WorkspaceLastChangedBy | Displays the display name of the user who last saved changes to the server copy of a shared document. Read-only.


Sync Properties (Office)

 Copy code hover
[image]

Sync Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the Sync object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the Sync object was created. Read-only.
ErrorType | Gets a MsoSyncErrorType constant which indicates the type of the most recent document synchronization error. Read-only.
LastSyncTime | Gets the date and time when the local copy of the active document was last synchronized with the server copy. Read-only.
Parent | Gets the Parent object for the Sync object. Read-only.
Status | Gets the status of the synchronization of the local copy of the active document with the server copy. Read-only.
WorkspaceLastChangedBy | Displays the display name of the user who last saved changes to the server copy of a shared document. Read-only.


Sync.Application Property (Office)

 Copy code hover
[image]

Sync.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the Sync object (you can use this property with an Automation object to return that object's container application). Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Application

expression A variable that represents a Sync object.

Return Value

Object

See also

Concepts

Sync Object

Other resources

Sync Object Members


Sync.Creator Property (Office)

 Copy code hover
[image]

Sync.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the Sync object was created. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Creator

expression A variable that represents a Sync object.

Return Value

Long

See also

Concepts

Sync Object

Other resources

Sync Object Members


Sync.ErrorType Property (Office)

 Copy code hover
[image]

Sync.ErrorType Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a MsoSyncErrorType constant which indicates the type of the most recent document synchronization error. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ErrorType

expression A variable that returns a Sync object.

Return Value

MsoSyncErrorType

Remarks

Use the ErrorType property to determine the type of the most recent document synchronization error. Not all document synchronization problems raise trappable run-time errors. After performing an operation using the Sync object, it's a good idea to check the Status property; if the Status property is msoSyncStatusError, check the ErrorType property for additional information on the type of error that has occurred.

See also

Concepts

Sync Object

Other resources

Sync Object Members


Sync.LastSyncTime Property (Office)

 Copy code hover
[image]

Sync.LastSyncTime Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the date and time when the local copy of the active document was last synchronized with the server copy. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .LastSyncTime

expression A variable that represents a Sync object.

Remarks

Use the LastSyncTime property to determine how much time has elapsed since the local copy of the active document was last synchronized with the server copy. Check the Status property to determine whether the local copy and the server copy are out of sync.

If the active document is not configured for synchronization between the local copy and the server copy, the LastSyncTime property raises a run-time error.

Example

The following example alerts the user and displays the sync status if more than 24 hours have elapsed since the LastSyncTime.

Copy code Copy code
    Dim objSync As Office.Sync
    Dim dtmLastSync As Date
    Dim strStatus As String
    Set objSync = ActiveDocument.Sync
    dtmLastSync = CDate(objSync.LastSyncTime)
    If DateDiff("h", dtmLastSync, Now) > 24 Then
        strStatus = "Document has not been synced " & _
            " within the last 24 hours." & vbCrLf & _
            "Document status: " & objSync.Status
        MsgBox strStatus, vbInformation + vbOKOnly, "Error Information"
    End If
    Set objSync = Nothing

See also

Concepts

Sync Object

Other resources

Sync Object Members


Sync.Parent Property (Office)

 Copy code hover
[image]

Sync.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the Sync object. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Parent

expression A variable that represents a Sync object.

Return Value

Object

See also

Concepts

Sync Object

Other resources

Sync Object Members


Sync.Status Property (Office)

 Copy code hover
[image]

Sync.Status Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the status of the synchronization of the local copy of the active document with the server copy. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Status

expression Required. A variable that represents a Sync object.

Remarks

Use the Status property to determine whether the local copy of the active document is synchronized with the shared server copy. Use the GetUpdate method to refresh the status. Use the following methods and properties when appropriate to respond to various status conditions:

  • msoSyncStatusConflict - True when both the local and the server copies have changes. Use the ResolveConflict method to resolve the differences.

  • msoSyncStatusError - Check the ErrorType property.

  • msoSyncStatusLocalChanges - True when only the local copy has changes. Use the PutUpdate method to save local changes to the server copy.

  • msoSyncStatusNewerAvailable - True when only the server copy has changes. Close and re-open the document to work with the latest copy from the server.

  • msoSyncStatusSuspended - Use the Unsuspend method to resume synchronization.

The Status property returns a single constant from the list in the following order of precedence:

  1. msoSyncStatusNoSharedWorkspace

  2. msoSyncStatusError

  3. msoSyncStatusSuspended

  4. msoSyncStatusConflict

  5. msoSyncStatusNewerAvailable

  6. msoSyncStatusLocalChanges

  7. msoSyncStatusLatest

Example

The following example examines the Status property and takes an appropriate action to synchronize the local and server copies of the document if necessary.

VBA Copy code Copy code
    Dim objSync As Office.Sync
    Dim strStatus As String
    Set objSync = ActiveDocument.Sync
    If objSync.Status > msoSyncStatusNoSharedWorkspace Then
        Select Case objSync.Status
            Case msoSyncStatusConflict
                objSync.ResolveConflict msoSyncConflictMerge
                ActiveDocument.Save
                objSync.ResolveConflict msoSyncConflictClientWins
                strStatus = "Conflict resolved by merging changes."
            Case msoSyncStatusError
                strStatus = "Last error type: " & objSync.ErrorType
            Case msoSyncStatusLatest
                strStatus = "Document copies already in sync."
            Case msoSyncStatusLocalChanges
                objSync.PutUpdate
                strStatus = "Local changes saved to server."
            Case msoSyncStatusNewerAvailable
                strStatus = "Newer copy available on the server."
            Case msoSyncStatusSuspended
                objSync.Unsuspend
                strStatus = "Synchronization resumed."
        End Select
    Else
        strStatus = "Not a shared workspace document."
    End If
    MsgBox strStatus, vbInformation + vbOKOnly, "Sync Information"
    Set objSync = Nothing

See also

Concepts

Sync Object

Other resources

Sync Object Members


Sync.WorkspaceLastChangedBy Property (Office)

 Copy code hover
[image]

Sync.WorkspaceLastChangedBy Property (Office)
See also Send feedback

Published: July 09, 2012

Displays the display name of the user who last saved changes to the server copy of a shared document. Read-only.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .WorkspaceLastChangedBy

expression A variable that represents a Sync object.

Remarks

If the active document is not configured for synchronization between the local copy and the server copy, the WorkspaceLastChangedBy property raises a run-time error.

Example

The following example checks for a conflict between the local and the server copies of the shared document and reports the name of the user who last saved changes to the server copy.

Copy code Copy code
    Dim objSync As Office.Sync
    Dim strStatus As String
    Set objSync = ActiveDocument.Sync
    If objSync.Status = msoSyncStatusConflict Then
        strStatus = "The server copy has been changed." & vbCrLf & _
            "Changes have been made by: " & _
            objSync.WorkspaceLastChangedBy
        MsgBox strStatus, vbInformation + vbOKOnly, "Server Copy Changed"
    End If
    Set objSync = Nothing

See also

Concepts

Sync Object

Other resources

Sync Object Members


Sync Methods (Office)

 Copy code hover
[image]

Sync Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
GetUpdate | Compares the local version of the shared document to the version on the server.
OpenVersion | Opens a different version of the shared document alongside the currently open local version.
PutUpdate | Updates the server copy of the shared document with the local copy.
ResolveConflict | Resolves conflicts between the local and the server copies of a shared document.
Unsuspend | Resumes synchronization between the local copy and the server copy of a shared document.


Sync.GetUpdate Method (Office)

 Copy code hover
[image]

Sync.GetUpdate Method (Office)
Send feedback

Published: July 09, 2012

Compares the local version of the shared document to the version on the server.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .GetUpdate

expression A variable that represents a Sync object.

Remarks

Use the GetUpdate method to compare the local version of the shared document to the version on the server and to refresh the sync status.

Not all document synchronization problems raise trappable run-time errors. After performing an operation using the Sync object, it's a good idea to check the Status property; if the Status property is msoSyncStatusError, check the ErrorType property for additional information on the type of error that has occurred.

In many circumstances, the best way to resolve an error condition is to call the GetUpdate method. For example, if a call to PutUpdate results in an error condition, then a call to GetUpdate will reset the status to msoSyncStatusLocalChanges.

Example

The following example compares the local and server copies of the document using the GetUpdate method and reports whether the server has a newer copy.

Copy code Copy code
    Dim objSync As Office.Sync
    Dim strStatus As String
    Set objSync = ActiveDocument.Sync
    objSync.GetUpdate
    If objSync.Status = msoSyncStatusNewerAvailable Then
        strStatus = "A newer version is available on the server."
        MsgBox strStatus, vbInformation + vbOKOnly, "Sync Information"
    End If
    Set objSync = Nothing


Sync.OpenVersion Method (Office)

 Copy code hover
[image]

Sync.OpenVersion Method (Office)
See also Send feedback

Published: July 09, 2012

Opens a different version of the shared document alongside the currently open local version.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .OpenVersion(SyncVersionType)

expression A variable that represents a Sync object.

Parameters

Name | Required/Optional | Data Type | Description
SyncVersionType | Required | MsoSyncVersionType | Represents the type of version.

Remarks

Use the OpenVersion method to open the last version viewed (msoSyncVersionLastViewed) or the server copy (msoSyncVersionServer) of the shared document alongside the currently open local version.

The msoSyncVersionLastViewed option displays the copy of the document that is created whenever the user overwrites the local copy with the server copy. For example, if you call the ResolveConflict method with the msoSyncConflictServerWins option, then your local changes are saved and can be viewed by calling OpenVersion(msoSyncVersionLastViewed).

Not all document synchronization problems raise trappable run-time errors. After performing an operation using the Sync object, it's a good idea to check the Status property; if the Status property is msoSyncStatusError, check the ErrorType property for additional information on the type of error that has occurred.

Example

The following example prompts the user to open the server copy of the shared document alongside the currently open local version.

Copy code Copy code
    Dim objSync As Office.Sync
    Dim lngChoice As VbMsgBoxResult
    Set objSync = ActiveDocument.Sync
    lngChoice = MsgBox("View server copy?", _
        vbQuestion + vbOKCancel, "Open Server Version?")
    If lngChoice = vbOK Then
        objSync.OpenVersion msoSyncVersionServer
    End If
    Set objSync = Nothing

See also

Concepts

Sync Object

Other resources

Sync Object Members


Sync.PutUpdate Method (Office)

 Copy code hover
[image]

Sync.PutUpdate Method (Office)
See also Send feedback

Published: July 09, 2012

Updates the server copy of the shared document with the local copy.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .PutUpdate

expression A variable that represents a Sync object.

Remarks

The PutUpdate method can encounter a conflict condition if the client is unaware of recent changes to the server copy of the shared document. Call the GetUpdate method before calling PutUpdate to refresh the status of the server copy and to detect a possible conflict.

The PutUpdate method raises a run-time error if the local document has unsaved changes.

Not all document synchronization problems raise trappable run-time errors. After performing an operation using the Sync object, it's a good idea to check the Status property; if the Status property is msoSyncStatusError, check the ErrorType property for additional information on the type of error that has occurred.

In many circumstances, the best way to resolve an error condition is to call the GetUpdate method. For example, if a call to PutUpdate results in an error condition, then a call to GetUpdate will reset the status to msoSyncStatusLocalChanges.

Example

The following example updates the server copy of the document from the local copy using the PutUpdate method if the local copy has been edited.

Copy code Copy code
    Dim objSync As Office.Sync
    Dim strStatus As String
    Set objSync = ActiveDocument.Sync
    If objSync.Status = msoSyncStatusLocalChanges Then
        objSync.PutUpdate
        strStatus = "Local changes saved to server."
        MsgBox strStatus, vbInformation + vbOKOnly, "Sync Information"
    End If
    Set objSync = Nothing

See also

Concepts

Sync Object

Other resources

Sync Object Members


Sync.ResolveConflict Method (Office)

 Copy code hover
[image]

Sync.ResolveConflict Method (Office)
See also Send feedback

Published: July 09, 2012

Resolves conflicts between the local and the server copies of a shared document.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .ResolveConflict(SyncConflictResolution)

expression A variable that represents a Sync object.

Parameters

Name | Required/Optional | Data Type | Description
SyncConflictResolution | Required | MsoSyncConflictResolutionType | Specifies how conflicts should be resolved.

Remarks

Use the ResolveConflict method to resolve differences between the local copy of the active document and the server copy. Use the msoSyncConflictMerge option (not available for a Microsoft Excel Workbook) to merge the changes from each document into the other. Replace the server copy with local changes by using the msoSyncConflictClientWins option, or replace the local copy with the changed server copy by using the msoSyncConflictServerWins option.

The msoSyncConflictMerge option merges changes made to the server copy into the local copy, but does not actually resolve the conflict. To resolve the conflict with the merged changes winning, you must save the active document after merging changes, then call the ResolveConflict method again with the msoSyncConflictClientWins option.

The ResolveConflict method can encounter a conflict condition if the client is unaware of recent changes to the server copy of the shared document. Call the GetUpdate method before calling ResolveConflict to refresh the status of the server copy and to detect a possible conflict.

The ResolveConflict method raises a run-time error if the local document has unsaved changes or if no conflict exists between the 2 copies of the document.

Not all document synchronization problems raise trappable run-time errors. After performing an operation using the Sync object, it's a good idea to check the Status property; if the Status property is msoSyncStatusError, check the ErrorType property for additional information on the type of error that has occurred.

Example

The following example attempts to resolve a conflict by merging changes between the local and the server copies of the active document.

VBA Copy code Copy code
    Dim objSync As Office.Sync
    Dim strStatus As String
    Set objSync = ActiveDocument.Sync
    If objSync.Status = msoSyncStatusConflict Then
        objSync.ResolveConflict msoSyncConflictMerge
        ActiveDocument.Save
        objSync.ResolveConflict msoSyncConflictClientWins
        strStatus = "Conflict resolved by merging changes."
        MsgBox strStatus, vbInformation + vbOKOnly, "Sync Information"
    End If
    Set objSync = Nothing

See also

Concepts

Sync Object

Other resources

Sync Object Members


Sync.Unsuspend Method (Office)

 Copy code hover
[image]

Sync.Unsuspend Method (Office)
See also Send feedback

Published: July 09, 2012

Resumes synchronization between the local copy and the server copy of a shared document.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Syntax

expression .Unsuspend

expression A variable that represents a Sync object.

Remarks

Use the Unsuspend method to resume document synchronization when the Status property returns msoSyncStatusSuspended.

Not all document synchronization problems raise trappable run-time errors. After performing an operation using the Sync object, it's a good idea to check the Status property; if the Status property is msoSyncStatusError, check the ErrorType property for additional information on the type of error that has occurred.

Example

The following example resumes document synchronization if it has been suspended.

VBA Copy code Copy code
    Dim objSync As Office.Sync
    Set objSync = ActiveDocument.Sync
    If objSync.Status = msoSyncStatusSuspended Then
        objSync.Unsuspend
        MsgBox "Synchronization resumed.", _
            vbInformation + vbOKOnly, "Sync Status"
    End If
    Set objSync = Nothing

See also

Concepts

Sync Object

Other resources

Sync Object Members


TabStop2 Object (Office)

 Copy code hover
[image]

TabStop2 Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a single tab stop. The TabStop2 object is a member of the TabStops2 collection.

Remarks

Tab stops are indexed numerically from left to right along the ruler.

Example

The following example removes the first custom tab stop from the selected paragraphs.

VBA Copy code Copy code
Sub ClearTabStop()
 Selection.TextRange.ParagraphFormat.Tabs(1).Clear
End Sub

See also

Concepts

Object Model Reference

Other resources

TabStop2 Object Members


TabStop2 Members (Office)

 Copy code hover
[image]

TabStop2 Members (Office)
Send feedback

Published: July 09, 2012

Represents a single tab stop. The TabStop2 object is a member of the TabStops2 collection.

Methods

Name | Description
Clear | Removes the specified custom tab stop

Properties

Name | Description
Application | Gets an Application object that represents the container application for the TabStop2 object. Read-only.
Creator | Gets a 32-bit integer that represents the Microsoft Office application in which the TabStop2 object was created. Read-only.
Parent | Gets an Object that represents the Parent object for the TabStop2 object. Read-only.
Position | Gets or sets the position of a tab stop relative to the left margin. Read/write.
Type | Gets or sets the type of the TabStop2 object. Read/write.


TabStop2 Properties (Office)

 Copy code hover
[image]

TabStop2 Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the TabStop2 object. Read-only.
Creator | Gets a 32-bit integer that represents the Microsoft Office application in which the TabStop2 object was created. Read-only.
Parent | Gets an Object that represents the Parent object for the TabStop2 object. Read-only.
Position | Gets or sets the position of a tab stop relative to the left margin. Read/write.
Type | Gets or sets the type of the TabStop2 object. Read/write.


TabStop2.Application Property (Office)

 Copy code hover
[image]

TabStop2.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the TabStop2 object. Read-only.

Syntax

expression .Application

expression An expression that returns a TabStop2 object.

Return Value

Object

See also

Concepts

TabStop2 Object

Other resources

TabStop2 Object Members


TabStop2.Creator Property (Office)

 Copy code hover
[image]

TabStop2.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that represents the Microsoft Office application in which the TabStop2 object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a TabStop2 object.

Return Value

Long

See also

Concepts

TabStop2 Object

Other resources

TabStop2 Object Members


TabStop2.Parent Property (Office)

 Copy code hover
[image]

TabStop2.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Object that represents the Parent object for the TabStop2 object. Read-only.

Syntax

expression .Parent

expression An expression that returns a TabStop2 object.

Return Value

Object

See also

Concepts

TabStop2 Object

Other resources

TabStop2 Object Members


TabStop2.Position Property (Office)

 Copy code hover
[image]

TabStop2.Position Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the position of a tab stop relative to the left margin. Read/write.

Syntax

expression .Position

expression An expression that returns a TabStop2 object.

Return Value

Single

See also

Concepts

TabStop2 Object

Other resources

TabStop2 Object Members


TabStop2.Type Property (Office)

 Copy code hover
[image]

TabStop2.Type Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the type of the TabStop2 object. Read/write.

Syntax

expression .Type

expression An expression that returns a TabStop2 object.

Return Value

MsoTabStopType

Remarks

Examples of MsoTabStopType types include msoTabStopCenter, msoTabStopLeft, and msoTabStopRight.

See also

Concepts

TabStop2 Object

Other resources

TabStop2 Object Members


TabStop2 Methods (Office)

 Copy code hover
[image]

TabStop2 Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Clear | Removes the specified custom tab stop


TabStop2.Clear Method (Office)

 Copy code hover
[image]

TabStop2.Clear Method (Office)
See also Send feedback

Published: July 09, 2012

Removes the specified custom tab stop

Syntax

expression .Clear

expression An expression that returns a TabStop2 object.

Example

This example clears the first custom tab in the first paragraph of the active Microsoft Word document.

VBA Copy code Copy code
ActiveDocument.Paragraphs(1).TabStops2(1).Clear

See also

Concepts

TabStop2 Object

Other resources

TabStop2 Object Members


TabStops2 Object (Office)

 Copy code hover
[image]

TabStops2 Object (Office)
See also Send feedback

Published: July 09, 2012

The collection of TabStop2 objects.

Remarks

Tab stops are indexed numerically from left to right along the ruler.

Example

The following example removes the first custom tab stop from the first paragraph in the active Microsoft Publisher publication.

VBA Copy code Copy code
Sub ClearTabStop()
    ActiveDocument.Pages(1).Shapes(1).TextFrame.TextRange _
        .ParagraphFormat.Tabs(1).Clear
End Sub

See also

Concepts

Object Model Reference

Other resources

TabStops2 Object Members


TabStops2 Members (Office)

 Copy code hover
[image]

TabStops2 Members (Office)
Send feedback

Published: July 09, 2012

The collection of TabStop2 objects.

Methods

Name | Description
Add | Adds a new tab stop to the specified TabStops2 object.
Item | Gets an individual object from the TabStops2 collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the TabStops2 object. Read-only.
Count | Gets a Long indicating the number of items in the TabStops2 collection. Read-only.
Creator | Gets a 32-bit integer that represents the Microsoft Office application in which the TabStops2 object was created. Read-only.
DefaultSpacing | Gets or sets the default spacing between tab stops. Read/write.
Parent | Gets an Object that represents the Parent object of the specified TabStops2 object. Read-only.


TabStops2 Properties (Office)

 Copy code hover
[image]

TabStops2 Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the TabStops2 object. Read-only.
Count | Gets a Long indicating the number of items in the TabStops2 collection. Read-only.
Creator | Gets a 32-bit integer that represents the Microsoft Office application in which the TabStops2 object was created. Read-only.
DefaultSpacing | Gets or sets the default spacing between tab stops. Read/write.
Parent | Gets an Object that represents the Parent object of the specified TabStops2 object. Read-only.


TabStops2.Application Property (Office)

 Copy code hover
[image]

TabStops2.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the TabStops2 object. Read-only.

Syntax

expression .Application

expression An expression that returns a TabStops2 object.

Return Value

Object

See also

Concepts

TabStops2 Object

Other resources

TabStops2 Object Members


TabStops2.Count Property (Office)

 Copy code hover
[image]

TabStops2.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the TabStops2 collection. Read-only.

Syntax

expression .Count

expression An expression that returns a TabStops2 object.

Return Value

Long

See also

Concepts

TabStops2 Object

Other resources

TabStops2 Object Members


TabStops2.Creator Property (Office)

 Copy code hover
[image]

TabStops2.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that represents the Microsoft Office application in which the TabStops2 object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a TabStops2 object.

Return Value

Long

See also

Concepts

TabStops2 Object

Other resources

TabStops2 Object Members


TabStops2.DefaultSpacing Property (Office)

 Copy code hover
[image]

TabStops2.DefaultSpacing Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the default spacing between tab stops. Read/write.

Syntax

expression .DefaultSpacing

expression An expression that returns a TabStops2 object.

Return Value

Single

See also

Concepts

TabStops2 Object

Other resources

TabStops2 Object Members


TabStops2.Parent Property (Office)

 Copy code hover
[image]

TabStops2.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Object that represents the Parent object of the specified TabStops2 object. Read-only.

Syntax

expression .Parent

expression An expression that returns a TabStops2 object.

Return Value

Object

See also

Concepts

TabStops2 Object

Other resources

TabStops2 Object Members


TabStops2 Methods (Office)

 Copy code hover
[image]

TabStops2 Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Add | Adds a new tab stop to the specified TabStops2 object.
Item | Gets an individual object from the TabStops2 collection.


TabStops2.Add Method (Office)

 Copy code hover
[image]

TabStops2.Add Method (Office)
See also Send feedback

Published: July 09, 2012

Adds a new tab stop to the specified TabStops2 object.

Syntax

expression .Add(Type, Position)

expression An expression that returns a TabStops2 object.

Parameters

Name | Required/Optional | Data Type | Description
Type | Required | MsoTabStopType | The type of tab stop to add.
Position | Required | Single | The horizontal position of the new tab stop relative to the left edge of the text frame. Numeric values are evaluated in points; strings are evaluated in the units specified and can be in any measurement unit supported by the Microsoft Office product.

Return Value

TabStop2

Remarks

Examples of MsoTabStopType types include msoTabStopCenter, msoTabStopLeft, and msoTabStopRight.

See also

Concepts

TabStops2 Object

Other resources

TabStops2 Object Members


TabStops2.Item Method (Office)

 Copy code hover
[image]

TabStops2.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Gets an individual object from the TabStops2 collection.

Syntax

expression .Item(Index)

expression An expression that returns a TabStops2 object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | The number of the object to return.

Return Value

TabStop2

See also

Concepts

TabStops2 Object

Other resources

TabStops2 Object Members


TextColumn2 Object (Office)

 Copy code hover
[image]

TextColumn2 Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a single text column. The TextColumn2 object is a member of the TextColumns2 collection.

Remarks

Use TextColumns2(Index), where Index is the index number, to return a single TextColumn2 object. The index number represents the position of the column in the TextColumns2 collection (counting from left to right).

Example

Use the Add method to add a column to the collection of columns. By default, there's one text column in the TextColumns2 collection. The following example adds a 2.5-inch-widecolumn to the active Microsoft Word document.

VBA Copy code Copy code
ActiveDocument.PageSetup.TextColumns2.Add _
 Width:=InchesToPoints(2.5), _
 Spacing:=InchesToPoints(0.5), EvenlySpaced:=False

See also

Concepts

Object Model Reference

Other resources

TextColumn2 Object Members


TextColumn2 Members (Office)

 Copy code hover
[image]

TextColumn2 Members (Office)
Send feedback

Published: July 09, 2012

Represents a single text column. The TextColumn2 object is a member of the TextColumns2 collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the TextColumn2 object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the TextColumn2 object was created. Read-only.
Number | Gets or sets the index of the TextColumn2 object. Read/write
Spacing | Gets or sets the spacing between text columns in a TextColumn2 object. Read/write.
TextDirection | Gets or sets the direction of text in the TextColumn2 object. Read/write.


TextColumn2 Properties (Office)

 Copy code hover
[image]

TextColumn2 Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the TextColumn2 object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the TextColumn2 object was created. Read-only.
Number | Gets or sets the index of the TextColumn2 object. Read/write
Spacing | Gets or sets the spacing between text columns in a TextColumn2 object. Read/write.
TextDirection | Gets or sets the direction of text in the TextColumn2 object. Read/write.


TextColumn2.Application Property (Office)

 Copy code hover
[image]

TextColumn2.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the TextColumn2 object. Read-only.

Syntax

expression .Application

expression An expression that returns a TextColumn2 object.

Return Value

Object

See also

Concepts

TextColumn2 Object

Other resources

TextColumn2 Object Members


TextColumn2.Count Property (Office)

 Copy code hover
[image]

TextColumn2.Count Property (Office)
Send feedback

Published: July 09, 2012

Gets or sets a Long indicating the number of items in the TextColumn2 collection. Read/write.

Syntax

expression .Count

expression An expression that returns a TextColumn2 object.

Return Value

Long


TextColumn2.Creator Property (Office)

 Copy code hover
[image]

TextColumn2.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the TextColumn2 object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a TextColumn2 object.

Return Value

Long

See also

Concepts

TextColumn2 Object

Other resources

TextColumn2 Object Members


TextColumn2.Number Property (Office)

 Copy code hover
[image]

TextColumn2.Number Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the index of the TextColumn2 object. Read/write

Syntax

expression .Number

expression An expression that returns a TextColumn2 object.

Return Value

Integer

See also

Concepts

TextColumn2 Object

Other resources

TextColumn2 Object Members


TextColumn2.Spacing Property (Office)

 Copy code hover
[image]

TextColumn2.Spacing Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the spacing between text columns in a TextColumn2 object. Read/write.

Syntax

expression .Spacing

expression An expression that returns a TextColumn2 object.

Return Value

Single

See also

Concepts

TextColumn2 Object

Other resources

TextColumn2 Object Members


TextColumn2.TextDirection Property (Office)

 Copy code hover
[image]

TextColumn2.TextDirection Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the direction of text in the TextColumn2 object. Read/write.

Syntax

expression .TextDirection

expression An expression that returns a TextColumn2 object.

Return Value

MsoTextDirection

Remarks

Examples of MsoTextDirection include msoTextDirectionLeftToRight, msoTextDirectionRightToLeft, and msoTextDirectionMixed.

See also

Concepts

TextColumn2 Object

Other resources

TextColumn2 Object Members


TextFrame2 Object (Office)

 Copy code hover
[image]

TextFrame2 Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the text frame in a Shape or ShapeRange object. Contains the text in the text frame and exposes properties and methods that control the alignment and anchoring of the text frame.

Version Information

Version Added: Office 2010

Remarks

Use the TextFrame2 property of the Shape and ShapeRange objects to return a TextFrame2 object.

Example

The following code adds a rectangle to a slide, adds text to the rectangle, and then sets the margins for the text frame.

VBA Copy code Copy code
Set pptSlide = ActivePresentation.Slides(1)
With pptSlide.Shapes.AddShape(msoShapeRectangle, 0, 0, 250, 140).TextFrame2
 .TextRange.Text = "Here is some sample text"
 .MarginBottom = 10
 .MarginLeft = 10
 .MarginRight = 10
 .MarginTop = 10
End With

See also

Concepts

Object Model Reference

Other resources

TextFrame2 Object Members


TextFrame2 Members (Office)

 Copy code hover
[image]

TextFrame2 Members (Office)
Send feedback

Published: July 09, 2012

Represents the text frame in a Shape or ShapeRange object. Contains the text in the text frame and exposes properties and methods that control the alignment and anchoring of the text frame.

Methods

Name | Description
DeleteText | Deletes the text from a text frame and all the associated properties of the text, including font attributes.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the TextFrame2 object. Read-only
AutoSize | Returns or sets a value that indicates whether the size of the specified shape is changed automatically to fit text within its boundaries. Read/write
Column | Returns the Column object that represents the columns of the specified text frame. Read-only
Creator | Returns a 32-bit integer that indicates the application in which this object was created. Read-only. Long
HasText | Indicates whether the shape that contains the specified text frame has text associated with it. Read-only
HorizontalAnchor | Returns or sets the horizontal alignment of text in a text frame. Read/write
MarginBottom | Returns or sets the distance (in points) between the bottom of the text frame and the bottom of the inscribed rectangle of the shape that contains the text. Read/write
MarginLeft | Returns or sets the distance (in points) between the left edge of the text frame and the left edge of the inscribed rectangle of the shape that contains the text. Read/write
MarginRight | Returns or sets the distance (in points) between the right edge of the text frame and the right edge of the inscribed rectangle of the shape that contains the text. Read/write
MarginTop | Returns or sets the distance (in points) between the top of the text frame and the top of the inscribed rectangle of the shape that contains the text. Read/write
NoTextRotation | Returns or sets a value that specifies if the text on a shape is rotated if the shape itself is being rotated. Read/write
Orientation | Returns or sets text orientation. Read/write
Parent | Returns the calling object. Read-only
PathFormat | Returns or sets the path type for the specified text frame. Read/write
Ruler | Returns a Ruler2 object that represents the ruler for the specified text. Read-only
TextRange | Sets the text for a range of nodes in a SmartArt object. Read-only
ThreeD | Returns a ThreeDFormat object that represents the three-dimensional formatting of the parent shape. Read-only
VerticalAnchor | Returns or sets the vertical alignment of text in a text frame. Read/write
WarpFormat | Returns or sets the warp format (how the text is warped) for the specified text frame. Read/write
WordArtformat | Returns or sets the WordArt type for the specified text frame. Read/write
WordWrap | Determines whether lines of text break automatically to fit inside the shape. Read/write


TextFrame2 Properties (Office)

 Copy code hover
[image]

TextFrame2 Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the TextFrame2 object. Read-only
AutoSize | Returns or sets a value that indicates whether the size of the specified shape is changed automatically to fit text within its boundaries. Read/write
Column | Returns the Column object that represents the columns of the specified text frame. Read-only
Creator | Returns a 32-bit integer that indicates the application in which this object was created. Read-only. Long
HasText | Indicates whether the shape that contains the specified text frame has text associated with it. Read-only
HorizontalAnchor | Returns or sets the horizontal alignment of text in a text frame. Read/write
MarginBottom | Returns or sets the distance (in points) between the bottom of the text frame and the bottom of the inscribed rectangle of the shape that contains the text. Read/write
MarginLeft | Returns or sets the distance (in points) between the left edge of the text frame and the left edge of the inscribed rectangle of the shape that contains the text. Read/write
MarginRight | Returns or sets the distance (in points) between the right edge of the text frame and the right edge of the inscribed rectangle of the shape that contains the text. Read/write
MarginTop | Returns or sets the distance (in points) between the top of the text frame and the top of the inscribed rectangle of the shape that contains the text. Read/write
NoTextRotation | Returns or sets a value that specifies if the text on a shape is rotated if the shape itself is being rotated. Read/write
Orientation | Returns or sets text orientation. Read/write
Parent | Returns the calling object. Read-only
PathFormat | Returns or sets the path type for the specified text frame. Read/write
Ruler | Returns a Ruler2 object that represents the ruler for the specified text. Read-only
TextRange | Sets the text for a range of nodes in a SmartArt object. Read-only
ThreeD | Returns a ThreeDFormat object that represents the three-dimensional formatting of the parent shape. Read-only
VerticalAnchor | Returns or sets the vertical alignment of text in a text frame. Read/write
WarpFormat | Returns or sets the warp format (how the text is warped) for the specified text frame. Read/write
WordArtformat | Returns or sets the WordArt type for the specified text frame. Read/write
WordWrap | Determines whether lines of text break automatically to fit inside the shape. Read/write


TextFrame2.Application Property (Office)

 Copy code hover
[image]

TextFrame2.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the TextFrame2 object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Application

expression An expression that returns a TextFrame2 object.

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.AutoSize Property (Office)

 Copy code hover
[image]

TextFrame2.AutoSize Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets a value that indicates whether the size of the specified shape is changed automatically to fit text within its boundaries. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .AutoSize

expression An expression that returns a TextFrame2 object.

Remarks

The value of the AutoSize property can be one of the following MsoAutoSize constants.

msoAutoSizeMixed

msoAutoSizeNone

msoAutoSizeShapeToFitText

msoAutoSizeTextToFitShape

Example

The following code shows how to adjust the size of the title text on slide one to fit the text frame that contains it.

VBA Copy code Copy code
Dim pptSlide As Slide
 Set pptSlide = ActivePresentation.Slides(1)
With pptSlide.Shapes(1)
 If .TextFrame2.TextRange.Characters.Count < 50 Then
 .TextFrame2.AutoSize = msoAutoSizeTextToFitShape
 End If
End With

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.Column Property (Office)

 Copy code hover
[image]

TextFrame2.Column Property (Office)
Send feedback

Published: July 09, 2012

Returns the Column object that represents the columns of the specified text frame. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Column

expression An expression that returns a TextFrame2 object.

Example

The following code shows how to set the number of columns in the text frame of the first shape on slide one to 2.

VBA Copy code Copy code
 ActivePresentation.Slides(1).Shapes(1).TextFrame2.Column.Number = 2


TextFrame2.Creator Property (Office)

 Copy code hover
[image]

TextFrame2.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Returns a 32-bit integer that indicates the application in which this object was created. Read-only. Long

Version Information

Version Added: Office 2010

Syntax

expression .Creator

expression An expression that returns a TextFrame2 object.

Example

This example displays a message about the creator of an Excel workbook. In this example, the hexadecimal number 5843454C is equivalent to the string XCEL which indicates that this object was created in Excel.

VBA Copy code Copy code
Sub FindCreator()

 Dim myObject As Excel.Workbook
 Set myObject = ActiveWorkbook
 If myObject.TextFrame2.Creator = &h5843454c Then
 MsgBox "This is a Microsoft Excel object."
 Else
 MsgBox "This is not a Microsoft Excel object."
 End If

End Sub

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.HasText Property (Office)

 Copy code hover
[image]

TextFrame2.HasText Property (Office)
See also Send feedback

Published: July 09, 2012

Indicates whether the shape that contains the specified text frame has text associated with it. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .HasText

expression An expression that returns a TextFrame2 object.

Remarks

The value of the HasText property can be one of the following MsoTriState constants.

Constant | Description
msoFalse | The specified text frame does not have text.
msoTrue | The specified text frame has text.

Example

The following code tests whether shape two on slide one contains text, and if it does, resizes the shape to fit the text.

VBA Copy code Copy code
Dim pptSlide As Slide
Set pptSlide = ActivePresentation.Slides(1)
 With pptSlide.Shapes(2).TextFrame
 If .HasText Then .AutoSize = ppAutoSizeShapeToFitText
 End With

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.HorizontalAnchor Property (Office)

 Copy code hover
[image]

TextFrame2.HorizontalAnchor Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets the horizontal alignment of text in a text frame. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .HorizontalAnchor

expression An expression that returns a TextFrame2 object.

Remarks

The value of the HorizontalAnchor property can be one of these MsoHorizontalAnchor constants.

msoAnchorNone

msoHorizontalAnchorMixed

msoAnchorCenter

Example

The following code shows how to set the alignment for shape one on slide one to top center.

VBA Copy code Copy code
With ActivePresentation.Slides(1).Shapes(1)
 .TextFrame2.HorizontalAnchor = msoAnchorCenter
 .TextFrame2.VerticalAnchor = msoAnchorTop
End With

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.MarginBottom Property (Office)

 Copy code hover
[image]

TextFrame2.MarginBottom Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets the distance (in points) between the bottom of the text frame and the bottom of the inscribed rectangle of the shape that contains the text. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .MarginBottom

expression An expression that returns a TextFrame2 object.

Example

The following code adds a rectangle to a slide, adds text to the rectangle, and then sets the margins for the text frame.

VBA Copy code Copy code
Set pptSlide = ActivePresentation.Slides(1)
With pptSlide.Shapes.AddShape(msoShapeRectangle, 0, 0, 250, 140).TextFrame2
 .TextRange.Text = "Here is some sample text"
 .MarginBottom = 10
 .MarginLeft = 10
 .MarginRight = 10
 .MarginTop = 10
End With

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.MarginLeft Property (Office)

 Copy code hover
[image]

TextFrame2.MarginLeft Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets the distance (in points) between the left edge of the text frame and the left edge of the inscribed rectangle of the shape that contains the text. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .MarginLeft

expression An expression that returns a TextFrame2 object.

Example

The following code adds a rectangle to a slide, adds text to the rectangle, and then sets the margins for the text frame.

VBA Copy code Copy code
Set pptSlide = ActivePresentation.Slides(1)
With pptSlide.Shapes.AddShape(msoShapeRectangle, 0, 0, 250, 140).TextFrame2
 .TextRange.Text = "Here is some sample text"
 .MarginBottom = 10
 .MarginLeft = 10
 .MarginRight = 10
 .MarginTop = 10
End With

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.MarginRight Property (Office)

 Copy code hover
[image]

TextFrame2.MarginRight Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets the distance (in points) between the right edge of the text frame and the right edge of the inscribed rectangle of the shape that contains the text. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .MarginRight

expression An expression that returns a TextFrame2 object.

Example

The following example adds a rectangle to a slide, adds text to the rectangle, and then sets the margins for the text frame.

VBA Copy code Copy code
Set pptSlide = ActivePresentation.Slides(1)
With pptSlide.Shapes.AddShape(msoShapeRectangle, 0, 0, 250, 140).TextFrame2
 .TextRange.Text = "Here is some sample text"
 .MarginBottom = 10
 .MarginLeft = 10
 .MarginRight = 10
 .MarginTop = 10
End With

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.MarginTop Property (Office)

 Copy code hover
[image]

TextFrame2.MarginTop Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets the distance (in points) between the top of the text frame and the top of the inscribed rectangle of the shape that contains the text. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .MarginTop

expression An expression that returns a TextFrame2 object.

Example

The following code adds a rectangle to a slide, adds text to the rectangle, and then sets the margins for the text frame.

VBA Copy code Copy code
Set pptSlide = ActivePresentation.Slides(1)
With pptSlide.Shapes.AddShape(msoShapeRectangle, 0, 0, 250, 140).TextFrame2
 .TextRange.Text = "Here is some sample text"
 .MarginBottom = 10
 .MarginLeft = 10
 .MarginRight = 10
 .MarginTop = 10
End With

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.NoTextRotation Property (Office)

 Copy code hover
[image]

TextFrame2.NoTextRotation Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets a value that specifies if the text on a shape is rotated if the shape itself is being rotated. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .NoTextRotation

expression An expression that returns a TextFrame2 object.

Remarks

Returns or sets MsoTriState enumerations with the following values:

  • msoCTrue

  • msoFalse

  • msoTriStateMixed

  • msoTriStateToggle

  • msoTrue

Example

The following example adds a rectangle to myDocument, adds text to the rectangle, sets the margins for the text frame, and then specifies that text rotation within the shape is not available.

VBA Copy code Copy code
Set myDocument = Worksheets(1)
With myDocument.Shapes.AddShape(msoShapeRectangle, _
 0, 0, 250, 140).TextFrame2
 .TextRange.Text = "Here is some test text"
 .MarginBottom = 10
 .MarginLeft = 10
 .MarginRight = 10
 .MarginTop = 10
 .NoTextRotation = msoFalse
End With

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.Orientation Property (Office)

 Copy code hover
[image]

TextFrame2.Orientation Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets text orientation. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .Orientation

expression An expression that returns a TextFrame2 object.

Remarks

The value of the Orientation property can be one of these MsoTextOrientation constants.

  • msoTextOrientationDownward

  • msoTextOrientationHorizontal

  • msoTextOrientationHorizontalRotatedFarEast

  • msoTextOrientationMixed

  • msoTextOrientationUpward

  • msoTextOrientationVertical

  • msoTextOrientationVerticalFarEast

Example

This example shows how to orient the text horizontally in shape one on slide one in the active presentation.

VBA Copy code Copy code
Dim pptSlide As Slide
Set pptSlide = ActivePresentation.Slides(1)
pptSlide.Shapes(1).TextFrame2.Orientation = msoTextOrientationHorizontal
Note Note

Some of these constants may not be available to you, depending on the language support (U.S. English, for example) that you've selected or installed.

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.Parent Property (Office)

 Copy code hover
[image]

TextFrame2.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Returns the calling object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Parent

expression An expression that returns a TextFrame2 object.

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.PathFormat Property (Office)

 Copy code hover
[image]

TextFrame2.PathFormat Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets the path type for the specified text frame. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .PathFormat

expression An expression that returns a TextFrame2 object.

Remarks

The value of the PathFormat property can be one of these MsoPathType constants. The value msoPathTypeMixed cannot be set. Setting the value msoPathTypeNone removes any existing path.

  • msoPathType1

  • msoPathType2

  • msoPathType3

  • msoPathType4

  • msoPathTypeMixed

  • msoPathTypeNone

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.Ruler Property (Office)

 Copy code hover
[image]

TextFrame2.Ruler Property (Office)
See also Send feedback

Published: July 09, 2012

Returns a Ruler2 object that represents the ruler for the specified text. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .Ruler

expression An expression that returns a TextFrame2 object.

Example

The following code shows how to set a left-aligned tab stop at 2 inches (144 points) for the text in shape one on slide one in the active presentation.

VBA Copy code Copy code
Dim pptSlide As Slide
Set pptSlide = ActivePresentation.Slides(1)
pptSlide.Shapes(1).TextFrame2.Ruler.TabStops.Add ppTabStopLeft, 144

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.TextRange Property (Office)

 Copy code hover
[image]

TextFrame2.TextRange Property (Office)
See also Send feedback

Published: July 09, 2012

Sets the text for a range of nodes in a SmartArt object. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .TextRange

expression An expression that returns a TextFrame2 object.

Example

The following example sets the text inside the first node.

VBA Copy code Copy code
smartart.AllNodes(1).TextFrame2.TextRange.Text="Node 1"

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.ThreeD Property (Office)

 Copy code hover
[image]

TextFrame2.ThreeD Property (Office)
See also Send feedback

Published: July 09, 2012

Returns a ThreeDFormat object that represents the three-dimensional formatting of the parent shape. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .ThreeD

expression An expression that returns a TextFrame2 object.

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.VerticalAnchor Property (Office)

 Copy code hover
[image]

TextFrame2.VerticalAnchor Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets the vertical alignment of text in a text frame. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .VerticalAnchor

expression An expression that returns a TextFrame2 object.

Remarks

The value of the VerticalAnchor property can be one of these MsoVerticalAnchor constants.

Example

The following example shows how to set the alignment for shape one on slide one to top center.

VBA Copy code Copy code
With ActivePresentation.Slides(1).Shapes(1)
 .TextFrame2.HorizontalAnchor = msoAnchorCenter
 .TextFrame2.VerticalAnchor = msoAnchorTop
End With

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.WarpFormat Property (Office)

 Copy code hover
[image]

TextFrame2.WarpFormat Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets the warp format (how the text is warped) for the specified text frame. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .WarpFormat

expression An expression that returns a TextFrame2 object.

Remarks

The value of the WarpFormat property can be one of the MsoWarpFormat constants.

Example

The following code shows how to set the warp format for shape one on slide one of the active presentation.

VBA Copy code Copy code
Public Sub WarpFormat_Example()

 Dim pptSlide As Slide
 Set pptSlide = ActivePresentation.Slides(1)
 pptSlide.Shapes(1).TextFrame2.WarpFormat = msoWarpFormat15

End Sub

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.WordArtformat Property (Office)

 Copy code hover
[image]

TextFrame2.WordArtformat Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets the WordArt type for the specified text frame. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .WordArtformat

expression An expression that returns a TextFrame2 object.

Remarks

The value of the WordArtFormat property can be one of these MsoPresetTextEffect constants.

Example

The following code shows how to set the word art format for shape one on slide one in the active presentation.

VBA Copy code Copy code
Dim pptSlide As Slide
Set pptSlide = ActivePresentation.Slides(1)
pptSlide.Shapes(1).TextFrame2.WordArtFormat = msoTextEffect20

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2.WordWrap Property (Office)

 Copy code hover
[image]

TextFrame2.WordWrap Property (Office)
See also Send feedback

Published: July 09, 2012

Determines whether lines of text break automatically to fit inside the shape. Read/write

Version Information

Version Added: Office 2010

Syntax

expression .WordWrap

expression An expression that returns a TextFrame2 object.

Remarks

The value of the WordWrap property can be one of these MsoTriState constants.

Constant | Description
msoFalse | Lines of text do not break to fit within the shape boundaries.
msoTrue | Lines of text break to fit within the shape boundaries.

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextFrame2 Methods (Office)

 Copy code hover
[image]

TextFrame2 Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
DeleteText | Deletes the text from a text frame and all the associated properties of the text, including font attributes.


TextFrame2.DeleteText Method (Office)

 Copy code hover
[image]

TextFrame2.DeleteText Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes the text from a text frame and all the associated properties of the text, including font attributes.

Version Information

Version Added: Office 2010

Syntax

expression .DeleteText

expression An expression that returns a TextFrame2 object.

Return Value

Nothing

Example

The following code shows how to delete the text from shape one on slide one of the active presentation, if that shape contains text.

VBA Copy code Copy code
Dim pptSlide As Slide
Set pptSlide = ActivePresentation.Slides(1)
pptSlide.Shapes(1).TextFrame2.DeleteText

See also

Concepts

TextFrame2 Object

Other resources

TextFrame2 Object Members


TextRange2 Object (Office)

 Copy code hover
[image]

TextRange2 Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the text frame in a Shape or ShapeRange objects.

Remarks

This object contains the text in the text frame as well as the properties and methods that control the alignment and anchoring of the text frame. Use the TextFrame2 property to return a TextFrame2 object.

Example

The following example adds a rectangle to myDocument, adds text to the rectangle, and then sets the margins for the text frame.

VBA Copy code Copy code
Set myDocument = Worksheets(1)
With myDocument.Shapes.AddShape(msoShapeRectangle, _
 0, 0, 250, 140).TextFrame2
 .TextRange.Text = "Here is some test text"
 .MarginBottom = 10
 .MarginLeft = 10
 .MarginRight = 10
 .MarginTop = 10
End With

See also

Concepts

Object Model Reference

Other resources

TextRange2 Object Members


TextRange2 Members (Office)

 Copy code hover
[image]

TextRange2 Members (Office)
Send feedback

Published: July 09, 2012

Represents the text frame in a Shape or ShapeRange objects.

Methods

Name | Description
AddPeriods | Adds period (.) punctuation to the right side of the text contained in TextRange2 object for left-to-right languages and on the left side for right-to-left languages.
ChangeCase | Changes the case of a TextRange2 object to one of the values in the MsoTextChangeCase enumeration.
Copy | Copies a TextRange2 object.
Cut | Removes a portion or all of the text from a range of text.
Delete | Deletes a TextRange2 object.
Find | Searches a TextRange2 object for a subset of text.
InsertAfter | Inserts text to the right of the existing text in the TextRange2 object.
InsertBefore | Inserts text to the left of the existing text in the TextRange2 object.
InsertChartField | Inserts a field into the body of a data label in a chart.
InsertSymbol | Inserts a symbol from the specified font set into the range of text represented by the TextRange2 object.
Item | Gets the range of text specified by the index number from the TextRange2 object.
LtrRun | Returns a TextRange2 object that represents the specified subset of left-to-right text runs. A text run consists of a range of characters that share the same font attributes.
Paste | Pastes the contents of the Clipboard into the TextRange2 object.
PasteSpecial | Replaces the text range with the contents of the Clipboard in the format specified. If the paste succeeds, this method returns a TextRange2 object including the text range that was pasted.
RemovePeriods | Removes all period (.) punctuation from the text in the TextRange2 object.
Replace | Finds specific text in a text range, replaces the found text with a specified string, and returns a TextRange2 object that represents the first occurrence of the found text. Returns Nothing if no match is found.
RotatedBounds | Gets the coordinates of the vertices of the text bounding box for the specified text range. Read-only.
RtlRun | Returns a TextRange2 object that represents the specified subset of right-to-left text runs. A text run consists of a range of characters that share the same font attributes.
Select | Selects the TextRange2 object.
TrimText | Returns aTextRange2 object that represents the specified text that has the whitespace removed.

Properties

Name | Description
Application | Used without an object qualifier, this property returns an Application object that represents the current instance of the Microsoft Office application. Used with an object qualifier, this property returns an Application object that represents the creator of the TextRange2 object. When used with an OLE Automation object, it returns the object's application. Read-only.
BoundHeight | Gets the height, in points, of the text bounding box for the specified text. Read-only.
BoundLeft | Gets the left coordinate, in points, of the text bounding box for the specified text. Read-only.
BoundTop | Gets the top coordinate, in points, of the text bounding box for the specified text. Read-only.
BoundWidth | Gets the width, in points, of the text bounding box for the specified text. Read-only.
Characters | Read-only.
Count | Gets a Long indicating the number of items in the TextRange2 collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the TextRange2 object was created. Read-only.
Font | Returns a Font object that represents character formatting for the TextRange2 object. Read-only.
LanguageID | Gets or sets the MsoLanguageID value of the TextRange2 object. Read/write.
Length | Get a Long that represents the length of a text range. Read-only.
Lines | Returns a TextRange2 object that represents the specified subset of text lines. Read-only.
MathZones | Sets the starting point and length of a math zone within a text range. Read-only
ParagraphFormat | Returns a ParagraphFormat object that represents paragraph formatting for the specified text. Read-only.
Paragraphs | Gets a TextRange2 object that represents the specified subset of text paragraphs. Read-only.
Parent | Gets the Parent object for the TextRange2 object. Read-only.
Runs | Gets a TextRange2 object that represents the specified subset of text runs. A text run consists of a range of characters that share the same font attributes. Read-only.
Sentences | Returns a TextRange2 object that represents the specified subset of text sentences. Read-only.
Start | Gets a Long value indicating the starting point of the specified text range. Read-only.
Text | Gets or sets a String value that represents the text in a text range. Read/write.
Words | Gets a TextRange2 object that represents the specified subset of text words. Read-only.


TextRange2 Properties (Office)

 Copy code hover
[image]

TextRange2 Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Used without an object qualifier, this property returns an Application object that represents the current instance of the Microsoft Office application. Used with an object qualifier, this property returns an Application object that represents the creator of the TextRange2 object. When used with an OLE Automation object, it returns the object's application. Read-only.
BoundHeight | Gets the height, in points, of the text bounding box for the specified text. Read-only.
BoundLeft | Gets the left coordinate, in points, of the text bounding box for the specified text. Read-only.
BoundTop | Gets the top coordinate, in points, of the text bounding box for the specified text. Read-only.
BoundWidth | Gets the width, in points, of the text bounding box for the specified text. Read-only.
Characters | Read-only.
Count | Gets a Long indicating the number of items in the TextRange2 collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the TextRange2 object was created. Read-only.
Font | Returns a Font object that represents character formatting for the TextRange2 object. Read-only.
LanguageID | Gets or sets the MsoLanguageID value of the TextRange2 object. Read/write.
Length | Get a Long that represents the length of a text range. Read-only.
Lines | Returns a TextRange2 object that represents the specified subset of text lines. Read-only.
MathZones | Sets the starting point and length of a math zone within a text range. Read-only
ParagraphFormat | Returns a ParagraphFormat object that represents paragraph formatting for the specified text. Read-only.
Paragraphs | Gets a TextRange2 object that represents the specified subset of text paragraphs. Read-only.
Parent | Gets the Parent object for the TextRange2 object. Read-only.
Runs | Gets a TextRange2 object that represents the specified subset of text runs. A text run consists of a range of characters that share the same font attributes. Read-only.
Sentences | Returns a TextRange2 object that represents the specified subset of text sentences. Read-only.
Start | Gets a Long value indicating the starting point of the specified text range. Read-only.
Text | Gets or sets a String value that represents the text in a text range. Read/write.
Words | Gets a TextRange2 object that represents the specified subset of text words. Read-only.


TextRange2.Application Property (Office)

 Copy code hover
[image]

TextRange2.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Used without an object qualifier, this property returns an Application object that represents the current instance of the Microsoft Office application. Used with an object qualifier, this property returns an Application object that represents the creator of the TextRange2 object. When used with an OLE Automation object, it returns the object's application. Read-only.

Syntax

expression .Application

expression An expression that returns a TextRange2 object.

Return Value

Object

Example

This example displays the name of the application that created each linked OLE object on page one of the active Publisher publication.

VBA Copy code Copy code
Dim shpOle As Shape

For Each shpOle In ActiveDocument.Pages(1).Shapes
 If shpOle.Type = pbLinkedOLEObject Then
 MsgBox shpOle.OLEFormat.Application.Name
 End If
Next

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.BoundHeight Property (Office)

 Copy code hover
[image]

TextRange2.BoundHeight Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the height, in points, of the text bounding box for the specified text. Read-only.

Syntax

expression .BoundHeight

expression An expression that returns a TextRange2 object.

Return Value

Single

Remarks

The text bounding box is not the same as the TextFrame object. The TextFrame object represents the container in which the text can reside. The text bounding box represents the perimeter immediately surrounding the text.

Example

This example adds a rounded rectangle to slide one with the same dimensions as the text bounding box in a PowerPoint presentation.

VBA Copy code Copy code
With ActivePresentation.Slides(1).Shapes(1)
 Set txb = .TextFrame.Text
 Set roundRect = .AddShape(ppShapeRoundRect, _
 txb.BoundLeft, txb.BoundTop, txb.BoundWidth, txb.BoundHeight)
 roundRect.Fill.Transparency = 0.25
End With

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.BoundLeft Property (Office)

 Copy code hover
[image]

TextRange2.BoundLeft Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the left coordinate, in points, of the text bounding box for the specified text. Read-only.

Syntax

expression .BoundLeft

expression An expression that returns a TextRange2 object.

Return Value

Single

Remarks

The text bounding box is not the same as the TextFrame object. The TextFrame object represents the container in which the text can reside. The text bounding box represents the perimeter immediately surrounding the text.

Example

This example adds a rounded rectangle to slide one with the same dimensions as the text bounding box.

VBA Copy code Copy code
With ActivePresentation.Slides(1).Shapes(1)
 Set txb = .TextFrame.Text
 Set roundRect = .AddShape(ppShapeRoundRect, _
 txb.BoundLeft, txb.BoundTop, txb.BoundWidth, txb.BoundHeight)
 roundRect.Fill.Transparency = 0.25
End With

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.BoundTop Property (Office)

 Copy code hover
[image]

TextRange2.BoundTop Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the top coordinate, in points, of the text bounding box for the specified text. Read-only.

Syntax

expression .BoundTop

expression An expression that returns a TextRange2 object.

Return Value

Single

Remarks

The text bounding box is not the same as the TextFrame object. The TextFrame object represents the container in which the text can reside. The text bounding box represents the perimeter immediately surrounding the text.

Example

This example adds a rounded rectangle to slide one with the same dimensions as the text bounding box.

VBA Copy code Copy code
With ActivePresentation.Slides(1).Shapes(1)
 Set txb = .TextFrame.Text
 Set roundRect = .AddShape(ppShapeRoundRect, _
 txb.BoundLeft, txb.BoundTop, txb.BoundWidth, txb.BoundHeight)
 roundRect.Fill.Transparency = 0.25
End With

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.BoundWidth Property (Office)

 Copy code hover
[image]

TextRange2.BoundWidth Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the width, in points, of the text bounding box for the specified text. Read-only.

Syntax

expression .BoundWidth

expression An expression that returns a TextRange2 object.

Return Value

Single

Remarks

The text bounding box is not the same as the TextFrame object. The TextFrame object represents the container in which the text can reside. The text bounding box represents the perimeter immediately surrounding the text.

Example

This example adds a rounded rectangle to slide one with the same dimensions as the text bounding box.

VBA Copy code Copy code
With ActivePresentation.Slides(1).Shapes(1)
 Set txb = .TextFrame.Text
 Set roundRect = .AddShape(ppShapeRoundRect, _
 txb.BoundLeft, txb.BoundTop, txb.BoundWidth, txb.BoundHeight)
 roundRect.Fill.Transparency = 0.25
End With

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Characters Property (Office)

 Copy code hover
[image]

TextRange2.Characters Property (Office)
See also Send feedback

Published: July 09, 2012

Read-only.

Syntax

expression .Characters(Start, Length)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
Start | Optional | Long | The first character in the returned range.
Length | Optional | Long | The number of characters to be returned.

Return Value

TextRange2

Remarks

If both Start and Length are omitted, the returned range starts with the first character and ends with the last paragraph in the specified range.

If Start is specified but Length is omitted, the returned range contains one character.

If Length is specified but Start is omitted, the returned range starts with the first character in the specified range.

If Start is greater than the number of characters in the specified text, the returned range starts with the last character in the specified range.

If Length is greater than the number of characters from the specified starting character to the end of the text, the returned range contains all those characters.

Example

This example sets the text for shape two on slide one in the active presentation and then makes the second character a subscript character with a 20-percent offset.

Copy code Copy code
Dim charRange As TextRange2
With Application.ActivePresentation.Slides(1).Shapes(2)
 Set charRange = .TextFrame.TextRange2.InsertBefore("H2O")
 charRange.Characters(2).Font.BaselineOffset = -0.2
End With

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Count Property (Office)

 Copy code hover
[image]

TextRange2.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the TextRange2 collection. Read-only.

Syntax

expression .Count

expression An expression that returns a TextRange2 object.

Return Value

Long

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Creator Property (Office)

 Copy code hover
[image]

TextRange2.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the TextRange2 object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a TextRange2 object.

Return Value

Long

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Font Property (Office)

 Copy code hover
[image]

TextRange2.Font Property (Office)
See also Send feedback

Published: July 09, 2012

Returns a Font object that represents character formatting for the TextRange2 object. Read-only.

Syntax

expression .Font

expression An expression that returns a TextRange2 object.

Return Value

Font

Example

This example sets the formatting for the text in shape one on slide one in the active PowerPoint presentation.

VBA Copy code Copy code
With ActivePresentation.Slides(1).Shapes(1)
 With .TextFrame.TextRange2.Font
 .Size = 48
 .Name = "Palatino"
 .Bold = True
 .Color.RGB = RGB(255, 127, 255)
 End With
End With

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.LanguageID Property (Office)

 Copy code hover
[image]

TextRange2.LanguageID Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the MsoLanguageID value of the TextRange2 object. Read/write.

Syntax

expression .LanguageID

expression An expression that returns a TextRange2 object.

Return Value

MsoLanguageID

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Length Property (Office)

 Copy code hover
[image]

TextRange2.Length Property (Office)
See also Send feedback

Published: July 09, 2012

Get a Long that represents the length of a text range. Read-only.

Syntax

expression .Length

expression An expression that returns a TextRange2 object.

Return Value

Long

Example

This example adds a shape with text and rotates the shape without rotating the text in the active PowerPoint presentation.

Copy code Copy code
Sub SetTextRange()
 Dim shpStar As Shape
 Dim sldOne As Slide
 Dim effNew As Effect

 Set sldOne = ActivePresentation.Slides(1)
 Set shpStar = sldOne.Shapes.AddShape(Type:=msoShape5pointStar, _
 Left:=32, Top:=32, Width:=300, Height:=300)

 shpStar.TextFrame.TextRange2.Text = "Animated shape."

 Set effNew = sldOne.TimeLine.MainSequence.AddEffect(Shape:=shpStar, _
 EffectId:=msoAnimEffectPath5PointStar, Level:=msoAnimateTextByAllLevels, _
 Trigger:=msoAnimTriggerAfterPrevious)
 With effNew
 If .TextRangeStart = 0 And .TextRangeLength > 0 Then
 With .Behaviors.Add(Type:=msoAnimTypeRotation).RotationEffect
 .From = 0
 .To = 360
 End With
 .Timing.AutoReverse = msoTrue
 End If
 End With
End Sub

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Lines Property (Office)

 Copy code hover
[image]

TextRange2.Lines Property (Office)
See also Send feedback

Published: July 09, 2012

Returns a TextRange2 object that represents the specified subset of text lines. Read-only.

Syntax

expression .Lines(Start, Length)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
Start | Optional | Long | The first line in the returned range.
Length | Optional | Long | The number of lines to be returned.

Return Value

TextRange2

Remarks

If both Start and Length are omitted, the returned range starts with the first line and ends with the last paragraph in the specified range.

If Start is specified but Length is omitted, the returned range contains one line.

If Length is specified but Start is omitted, the returned range starts with the first line in the specified range.

If Start is greater than the number of lines in the specified text, the returned range starts with the last line in the specified range.

If Length is greater than the number of lines from the specified starting line to the end of the text, the returned range contains all those lines.

Example

This example formats as italic the first two lines of the second paragraph in shape two on slide one in the active PowerPoint presentation.

Copy code Copy code
Application.ActivePresentation.Slides(1).Shapes(2) _
 .TextFrame.TextRange2.Paragraphs(2) _
 .Lines(1, 2).Font.Italic = True

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.MathZones Property (Office)

 Copy code hover
[image]

TextRange2.MathZones Property (Office)
See also Send feedback

Published: July 09, 2012

Sets the starting point and length of a math zone within a text range. Read-only

Version Information

Version Added: Office 2010

Syntax

expression .MathZones(Start, Length)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
Start | Optional | Integer | The starting point for the math zone.
Length | Optional | Integer | The length of the math zone.

Remarks

A math zone is a text range within which math typography rules apply and outside of which math typography rules do not apply. In addition to containing special mathematical symbols, math zones can also contain text such as in the equation rate = distance/time where text appears with math symbols.

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.ParagraphFormat Property (Office)

 Copy code hover
[image]

TextRange2.ParagraphFormat Property (Office)
See also Send feedback

Published: July 09, 2012

Returns a ParagraphFormat object that represents paragraph formatting for the specified text. Read-only.

Syntax

expression .ParagraphFormat

expression An expression that returns a TextRange2 object.

Return Value

ParagraphFormat

Example

This example sets the line spacing before, within, and after each paragraph in shape two on slide one in the active PowerPoint presentation.

VBA Copy code Copy code
With Application.ActivePresentation.Slides(2).Shapes(2)
 With .TextFrame.TextRange2.ParagraphFormat
 .LineRuleWithin = msoTrue
 .SpaceWithin = 1.4
 .LineRuleBefore = msoTrue
 .SpaceBefore = 0.25
 .LineRuleAfter = msoTrue
 .SpaceAfter = 0.75
 End With
End With

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Paragraphs Property (Office)

 Copy code hover
[image]

TextRange2.Paragraphs Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a TextRange2 object that represents the specified subset of text paragraphs. Read-only.

Syntax

expression .Paragraphs(Start, Length)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
Start | Optional | Long | The first paragraph in the returned range.
Length | Optional | Long | The number of paragraphs to be returned.

Return Value

TextRange2

Remarks

If both Start and Length are omitted, the returned range starts with the first paragraph and ends with the last paragraph in the specified range.

If Start is specified but Length is omitted, the returned range contains one paragraph.

If Length is specified but Start is omitted, the returned range starts with the first paragraph in the specified range.

If Start is greater than the number of paragraphs in the specified text, the returned range starts with the last paragraph in the specified range.

If Length is greater than the number of paragraphs from the specified starting paragraph to the end of the text, the returned range contains all those paragraphs.

Example

This example formats as italic the first two lines of the second paragraph in shape two on slide one in the active PowerPoint presentation.

VBA Copy code Copy code
Application.ActivePresentation.Slides(1).Shapes(2) _
 .TextFrame.TextRange2.Paragraphs(2) _
 .Lines(1, 2).Font.Italic = True

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Parent Property (Office)

 Copy code hover
[image]

TextRange2.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the TextRange2 object. Read-only.

Syntax

expression .Parent

expression An expression that returns a TextRange2 object.

Return Value

Object

Example

This example adds an oval containing text to slide one in the active presentation and rotates the oval and the text 45 degrees. The parent object for the text frame is the Shape object that contains the text.

VBA Copy code Copy code
Set myShapes = ActivePresentation.Slides(1).Shapes
With myShapes.AddShape(Type:=msoShapeOval, Left:=50, _
 Top:=50, Width:=300, Height:=150).TextFrame
 .TextRange2.Text = "Test text"
 .Parent.Rotation = 45
End With

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Runs Property (Office)

 Copy code hover
[image]

TextRange2.Runs Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a TextRange2 object that represents the specified subset of text runs. A text run consists of a range of characters that share the same font attributes. Read-only.

Syntax

expression .Runs(Start, Length)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
Start | Optional | Long | The first run in the returned range.
Length | Optional | Long | The number of runs to be returned.

Return Value

TextRange2

Remarks

If both Start and Length are omitted, the returned range starts with the first run and ends with the last paragraph in the specified range.

If Start is specified but Length is omitted, the returned range contains one run.

If Length is specified but Start is omitted, the returned range starts with the first run in the specified range.

If Start is greater than the number of runs in the specified text, the returned range starts with the last run in the specified range.

If Length is greater than the number of runs from the specified starting run to the end of the text, the returned range contains all those runs.

A run consists of all characters from the first character after a font change to the second-to-last character with the same font attributes. For example, consider the following sentence:

This italic word is not bold.

In the preceding sentence, the first run consists of the word "This" only if the space after the word "This" isn't formatted as italic (if the space is italic, the first run is only the first three characters, or "Thi"). Likewise, the second run contains the word "italic" only if the space after the word is formatted as italic.

Example

This example formats the second run in shape two on slide one in the active presentation as bold italic if it's already italic.

Copy code Copy code
With Application.ActivePresentation.Slides(1).Shapes(2) _
        .TextFrame.TextRange2
    With .Runs(2).Font
        If .Italic Then
            .Bold = True
        End If
    End With
End With

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Sentences Property (Office)

 Copy code hover
[image]

TextRange2.Sentences Property (Office)
See also Send feedback

Published: July 09, 2012

Returns a TextRange2 object that represents the specified subset of text sentences. Read-only.

Syntax

expression .Sentences(Start, Length)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
Start | Optional | Long | The first sentence in the returned range.
Length | Optional | Long | The number of sentences to be returned.

Return Value

TextRange2

Remarks

If both Start and Length are omitted, the returned range starts with the first sentence and ends with the last paragraph in the specified range.

If Start is specified but Length is omitted, the returned range contains one sentence.

If Length is specified but Start is omitted, the returned range starts with the first sentence in the specified range.

If Start is greater than the number of sentences in the specified text, the returned range starts with the last sentence in the specified range.

If Length is greater than the number of sentences from the specified starting sentence to the end of the text, the returned range contains all those sentences.

Example

This example formats as bold the second sentence in the second paragraph in shape two on slide one in the active PowerPoint presentation.

Copy code Copy code
Application.ActivePresentation.Slides(1).Shapes(2) _
 .TextFrame.TextRange2.Paragraphs(2).Sentences(2).Font _
 .Bold = True

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Start Property (Office)

 Copy code hover
[image]

TextRange2.Start Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long value indicating the starting point of the specified text range. Read-only.

Syntax

expression .Start

expression An expression that returns a TextRange2 object.

Return Value

Long

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Text Property (Office)

 Copy code hover
[image]

TextRange2.Text Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a String value that represents the text in a text range. Read/write.

Syntax

expression .Text

expression An expression that returns a TextRange2 object.

Return Value

String

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Words Property (Office)

 Copy code hover
[image]

TextRange2.Words Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a TextRange2 object that represents the specified subset of text words. Read-only.

Syntax

expression .Words(Start, Length)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
Start | Optional | Long | The first word in the returned range.
Length | Optional | Long | The number of words to be returned.

Return Value

TextRange2

Remarks

If both Start and Length are omitted, the returned range starts with the first word and ends with the last paragraph in the specified range.

If Start is specified but Length is omitted, the returned range contains one word.

If Length is specified but Start is omitted, the returned range starts with the first word in the specified range.

If Start is greater than the number of words in the specified text, the returned range starts with the last word in the specified range.

If Length is greater than the number of words from the specified starting word to the end of the text, the returned range contains all those words.

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2 Methods (Office)

 Copy code hover
[image]

TextRange2 Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
AddPeriods | Adds period (.) punctuation to the right side of the text contained in TextRange2 object for left-to-right languages and on the left side for right-to-left languages.
ChangeCase | Changes the case of a TextRange2 object to one of the values in the MsoTextChangeCase enumeration.
Copy | Copies a TextRange2 object.
Cut | Removes a portion or all of the text from a range of text.
Delete | Deletes a TextRange2 object.
Find | Searches a TextRange2 object for a subset of text.
InsertAfter | Inserts text to the right of the existing text in the TextRange2 object.
InsertBefore | Inserts text to the left of the existing text in the TextRange2 object.
InsertChartField | Inserts a field into the body of a data label in a chart.
InsertSymbol | Inserts a symbol from the specified font set into the range of text represented by the TextRange2 object.
Item | Gets the range of text specified by the index number from the TextRange2 object.
LtrRun | Returns a TextRange2 object that represents the specified subset of left-to-right text runs. A text run consists of a range of characters that share the same font attributes.
Paste | Pastes the contents of the Clipboard into the TextRange2 object.
PasteSpecial | Replaces the text range with the contents of the Clipboard in the format specified. If the paste succeeds, this method returns a TextRange2 object including the text range that was pasted.
RemovePeriods | Removes all period (.) punctuation from the text in the TextRange2 object.
Replace | Finds specific text in a text range, replaces the found text with a specified string, and returns a TextRange2 object that represents the first occurrence of the found text. Returns Nothing if no match is found.
RotatedBounds | Gets the coordinates of the vertices of the text bounding box for the specified text range. Read-only.
RtlRun | Returns a TextRange2 object that represents the specified subset of right-to-left text runs. A text run consists of a range of characters that share the same font attributes.
Select | Selects the TextRange2 object.
TrimText | Returns aTextRange2 object that represents the specified text that has the whitespace removed.


TextRange2.AddPeriods Method (Office)

 Copy code hover
[image]

TextRange2.AddPeriods Method (Office)
See also Send feedback

Published: July 09, 2012

Adds period (.) punctuation to the right side of the text contained in TextRange2 object for left-to-right languages and on the left side for right-to-left languages.

Syntax

expression .AddPeriods

expression An expression that returns a TextRange2 object.

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.ChangeCase Method (Office)

 Copy code hover
[image]

TextRange2.ChangeCase Method (Office)
See also Send feedback

Published: July 09, 2012

Changes the case of a TextRange2 object to one of the values in the MsoTextChangeCase enumeration.

Syntax

expression .ChangeCase(Type)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
Type | Required | MsoTextChangeCase | Specifies the type of change to make to the text.

Remarks

Examples of MsoTextChangeCase enumeration include msoCaseLower, msoCaseUpper, and msoCaseTitle.

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Copy Method (Office)

 Copy code hover
[image]

TextRange2.Copy Method (Office)
See also Send feedback

Published: July 09, 2012

Copies a TextRange2 object.

Syntax

expression .Copy

expression An expression that returns a TextRange2 object.

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Cut Method (Office)

 Copy code hover
[image]

TextRange2.Cut Method (Office)
See also Send feedback

Published: July 09, 2012

Removes a portion or all of the text from a range of text.

Syntax

expression .Cut

expression An expression that returns a TextRange2 object.

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Delete Method (Office)

 Copy code hover
[image]

TextRange2.Delete Method (Office)
See also Send feedback

Published: July 09, 2012

Deletes a TextRange2 object.

Syntax

expression .Delete

expression An expression that returns a TextRange2 object.

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Find Method (Office)

 Copy code hover
[image]

TextRange2.Find Method (Office)
See also Send feedback

Published: July 09, 2012

Searches a TextRange2 object for a subset of text.

Syntax

expression .Find(FindWhat, After, MatchCase, WholeWords)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
FindWhat | Required | String | Contains the text to find.
After | Optional | Long | Specifies the point in the text range to start the search.
MatchCase | Optional | MsoTriState | Specifies if the target text must exactly match the case of the search text.
WholeWords | Optional | MsoTriState | Specifies that only whole words will be searched.

Return Value

TextRange2

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.InsertAfter Method (Office)

 Copy code hover
[image]

TextRange2.InsertAfter Method (Office)
See also Send feedback

Published: July 09, 2012

Inserts text to the right of the existing text in the TextRange2 object.

Syntax

expression .InsertAfter(NewText)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
NewText | Optional | String | Contains the text to be inserted.

Return Value

TextRange2

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.InsertBefore Method (Office)

 Copy code hover
[image]

TextRange2.InsertBefore Method (Office)
See also Send feedback

Published: July 09, 2012

Inserts text to the left of the existing text in the TextRange2 object.

Syntax

expression .InsertBefore(NewText)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
NewText | Optional | String | Contains the text to be inserted.

Return Value

TextRange2

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.InsertChartField Method (Office)

 Copy code hover
[image]

TextRange2.InsertChartField Method (Office)
Send feedback

Inserts a field into the body of a data label in a chart.

This method applies only to data labels in a chart. Calling this method on any other kind of TextRange2 object will raise a runtime error.

Version information

Version Added: Office 2013

Syntax

expression .InsertChartField(ChartFieldType,Formula,Position)

expression A variable that represents a TextRange2 object.

Parameters

Name | Required/Optional | Data type | Description
ChartFieldType | Required | MsoChartFieldType | Specifies the type of chart field to insert into a data label.
Formula | Optional | string | Specifies a cell (or range) if the MsoChartFieldFormula constant is passed in for the ChartFieldType parameter.
Position | Optional | integer | Specifies the character position where the chart field is inserted. The default is to append the field to the end of the text. If the position value is out of range, the default is used.
ChartFieldType | Required | MSOCHARTFIELDTYPE |
Formula | Optional | STRING |
Position | Optional | INT |

Return value

TextRange2


TextRange2.InsertSymbol Method (Office)

 Copy code hover
[image]

TextRange2.InsertSymbol Method (Office)
See also Send feedback

Published: July 09, 2012

Inserts a symbol from the specified font set into the range of text represented by the TextRange2 object.

Syntax

expression .InsertSymbol(FontName, CharNumber, Unicode)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
FontName | Required | String | The name of the font set.
CharNumber | Required | Long | The number of the symbol.
Unicode | Optional | MsoTriState | Indicates whether the value of the symbol is specified as a unicode value.

Return Value

TextRange2

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Item Method (Office)

 Copy code hover
[image]

TextRange2.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Gets the range of text specified by the index number from the TextRange2 object.

Syntax

expression .Item(Index)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Variant | The index number of the text range.

Return Value

TextRange2

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.LtrRun Method (Office)

 Copy code hover
[image]

TextRange2.LtrRun Method (Office)
See also Send feedback

Published: July 09, 2012

Returns a TextRange2 object that represents the specified subset of left-to-right text runs. A text run consists of a range of characters that share the same font attributes.

Syntax

expression .LtrRun

expression An expression that returns a TextRange2 object.

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Paste Method (Office)

 Copy code hover
[image]

TextRange2.Paste Method (Office)
See also Send feedback

Published: July 09, 2012

Pastes the contents of the Clipboard into the TextRange2 object.

Syntax

expression .Paste

expression An expression that returns a TextRange2 object.

Return Value

TextRange2

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.PasteSpecial Method (Office)

 Copy code hover
[image]

TextRange2.PasteSpecial Method (Office)
See also Send feedback

Published: July 09, 2012

Replaces the text range with the contents of the Clipboard in the format specified. If the paste succeeds, this method returns a TextRange2 object including the text range that was pasted.

Syntax

expression .PasteSpecial(Format)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
Format | Required | MsoClipboardFormat | Determines the format for the Clipboard contents when they're inserted into the document.

Return Value

TextRange2

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.RemovePeriods Method (Office)

 Copy code hover
[image]

TextRange2.RemovePeriods Method (Office)
See also Send feedback

Published: July 09, 2012

Removes all period (.) punctuation from the text in the TextRange2 object.

Syntax

expression .RemovePeriods

expression An expression that returns a TextRange2 object.

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Replace Method (Office)

 Copy code hover
[image]

TextRange2.Replace Method (Office)
See also Send feedback

Published: July 09, 2012

Finds specific text in a text range, replaces the found text with a specified string, and returns a TextRange2 object that represents the first occurrence of the found text. Returns Nothing if no match is found.

Syntax

expression .Replace(FindWhat, ReplaceWhat, After, MatchCase, WholeWords)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
FindWhat | Required | String | The text to search for.
ReplaceWhat | Required | String | The text you want to replace the found text with.
After | Optional | Long | The position of the character (in the specified text range) after which you want to search for the next occurrence of FindWhat. For example, if you want to search from the fifth character of the text range, specify 4 for After. If this argument is omitted, the first character of the text range is used as the starting point for the search.
MatchCase | Optional | MsoTriState | Determines whether a distinction is made on the basis of case.
WholeWords | Optional | MsoTriState | Determines whether only whole words are searched.

Return Value

TextRange2

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.RotatedBounds Method (Office)

 Copy code hover
[image]

TextRange2.RotatedBounds Method (Office)
See also Send feedback

Published: July 09, 2012

Gets the coordinates of the vertices of the text bounding box for the specified text range. Read-only.

Syntax

expression .RotatedBounds(X1, Y1, X2, Y2, X3, Y3, x4, y4)

expression An expression that returns a TextRange2 object.

Parameters

Name | Required/Optional | Data Type | Description
X1 | Required | Single | Returns the position (in points) of the X coordinate of the first vertex of the bounding box for the text within the specified text range.
Y1 | Required | Single | Returns the position (in points) of the Y coordinate of the first vertex of the bounding box for the text within the specified text range.
X2 | Required | Single | Returns the position (in points) of the X coordinate of the second vertex of the bounding box for the text within the specified text range.
Y2 | Required | Single | Returns the position (in points) of the Y coordinate of the second vertex of the bounding box for the text within the specified text range.
X3 | Required | Single | Returns the position (in points) of the X coordinate of the third vertex of the bounding box for the text within the specified text range.
Y3 | Required | Single | Returns the position (in points) of the Y coordinate of the third vertex of the bounding box for the text within the specified text range.
x4 | Required | Single | Returns the position (in points) of the X coordinate of the fourth vertex of the bounding box for the text within the specified text range.
y4 | Required | Single | Returns the position (in points) of the Y coordinate of the fourth vertex of the bounding box for the text within the specified text range.

Remarks

The text bounding box is not the same as the TextFrame2 object. The TextFrame2 object represents the container in which the text can reside. The text bounding box represents the perimeter immediately surrounding the text.

Example

This example uses the values returned by the arguments of the RotatedBounds method to draw a freeform that has the dimensions of the text bounding box for the third word in the text range in shape one on slide one in the active presentation.

VBA Copy code Copy code
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Dim x3 As Single, y3 As Single
Dim x4 As Single, y4 As Single
Dim myDocument As Slide

Set myDocument = ActivePresentation.Slides(1)
myDocument.Shapes(1).TextFrame2.TextRange2.Words(3).RotatedBounds _
 x1, y1, x2, y2, x3, y3, x4, y4
With myDocument.Shapes.BuildFreeform(msoEditingCorner, x1, y1)
 .AddNodes msoSegmentLine, msoEditingAuto, x2, y2
 .AddNodes msoSegmentLine, msoEditingAuto, x3, y3
 .AddNodes msoSegmentLine, msoEditingAuto, x4, y4
 .AddNodes msoSegmentLine, msoEditingAuto, x1, y1
 .ConvertToShape.ZOrder msoSendToBack
End With

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.RtlRun Method (Office)

 Copy code hover
[image]

TextRange2.RtlRun Method (Office)
See also Send feedback

Published: July 09, 2012

Returns a TextRange2 object that represents the specified subset of right-to-left text runs. A text run consists of a range of characters that share the same font attributes.

Syntax

expression .RtlRun

expression An expression that returns a TextRange2 object.

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.Select Method (Office)

 Copy code hover
[image]

TextRange2.Select Method (Office)
See also Send feedback

Published: July 09, 2012

Selects the TextRange2 object.

Syntax

expression .Select

expression An expression that returns a TextRange2 object.

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


TextRange2.TrimText Method (Office)

 Copy code hover
[image]

TextRange2.TrimText Method (Office)
See also Send feedback

Published: July 09, 2012

Returns aTextRange2 object that represents the specified text that has the whitespace removed.

Syntax

expression .TrimText

expression An expression that returns a TextRange2 object.

Return Value

TextRange2

See also

Concepts

TextRange2 Object

Other resources

TextRange2 Object Members


ThemeColor Object (Office)

 Copy code hover
[image]

ThemeColor Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a color in the color scheme of a Microsoft Office theme.

Example

The following example sets a ThemeColor object to the msoThemeAccent1 constant.

VBA Copy code Copy code
Dim tcsThemeColorScheme As ThemeColorScheme
Dim tcThemeColor As ThemeColor
Set tcThemeColor = tcsThemeColorScheme.Colors(msoThemeAccent1)

See also

Concepts

Object Model Reference

Other resources

ThemeColor Object Members


ThemeColor Members (Office)

 Copy code hover
[image]

ThemeColor Members (Office)
Send feedback

Published: July 09, 2012

Represents a color in the color scheme of a Microsoft Office theme.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeColor object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeColor object was created. Read-only.
Parent | Gets the Parent object for the ThemeColor object. Read-only.
RGB | Gets or sets a value of a color in the color scheme of a Microsoft Office theme. Read/write.
ThemeColorSchemeIndex | Gets the index value a color scheme of a Microsoft Office theme. Read-only.


ThemeColor Properties (Office)

 Copy code hover
[image]

ThemeColor Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeColor object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeColor object was created. Read-only.
Parent | Gets the Parent object for the ThemeColor object. Read-only.
RGB | Gets or sets a value of a color in the color scheme of a Microsoft Office theme. Read/write.
ThemeColorSchemeIndex | Gets the index value a color scheme of a Microsoft Office theme. Read-only.


ThemeColor.Application Property (Office)

 Copy code hover
[image]

ThemeColor.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ThemeColor object. Read-only.

Syntax

expression .Application

expression An expression that returns a ThemeColor object.

Return Value

Object

See also

Concepts

ThemeColor Object

Other resources

ThemeColor Object Members


ThemeColor.Creator Property (Office)

 Copy code hover
[image]

ThemeColor.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ThemeColor object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a ThemeColor object.

Return Value

Long

See also

Concepts

ThemeColor Object

Other resources

ThemeColor Object Members


ThemeColor.Parent Property (Office)

 Copy code hover
[image]

ThemeColor.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ThemeColor object. Read-only.

Syntax

expression .Parent

expression An expression that returns a ThemeColor object.

Return Value

Object

See also

Concepts

ThemeColor Object

Other resources

ThemeColor Object Members


ThemeColor.RGB Property (Office)

 Copy code hover
[image]

ThemeColor.RGB Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets a value of a color in the color scheme of a Microsoft Office theme. Read/write.

Syntax

expression .RGB

expression An expression that returns a ThemeColor object.

Return Value

MsoRGBType

See also

Concepts

ThemeColor Object

Other resources

ThemeColor Object Members


ThemeColor.ThemeColorSchemeIndex Property (Office)

 Copy code hover
[image]

ThemeColor.ThemeColorSchemeIndex Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the index value a color scheme of a Microsoft Office theme. Read-only.

Syntax

expression .ThemeColorSchemeIndex

expression An expression that returns a ThemeColor object.

Return Value

MsoThemeColorSchemeIndex

See also

Concepts

ThemeColor Object

Other resources

ThemeColor Object Members


ThemeColorScheme Object (Office)

 Copy code hover
[image]

ThemeColorScheme Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the color scheme of a Microsoft Office theme.

Example

The following example sets a ThemeColorScheme object to Red.

VBA Copy code Copy code
Dim tTheme As OfficeTheme
Dim tcsThemeColorScheme As ThemeColorScheme
Set tcsThemeColorScheme = tTheme.ThemeColorScheme

See also

Concepts

Object Model Reference

Other resources

ThemeColorScheme Object Members


ThemeColorScheme Members (Office)

 Copy code hover
[image]

ThemeColorScheme Members (Office)
Send feedback

Published: July 09, 2012

Represents the color scheme of a Microsoft Office theme.

Methods

Name | Description
Colors | Gets an object that represents a color in the color scheme of a Microsoft Office theme.
GetCustomColor | Gets a value that represents a color in the color scheme of a Microsoft Office theme.
Load | Loads the color scheme of a Microsoft Office theme from a file.
Save | Saves the color scheme of a Microsoft Office theme to a file.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeColorScheme object. Read-only.
Count | Gets a Integer indicating the number of items in the ThemeColorScheme collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeColorScheme object was created. Read-only.
Parent | Gets the Parent object for the ThemeColorScheme object. Read-only.


ThemeColorScheme Properties (Office)

 Copy code hover
[image]

ThemeColorScheme Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeColorScheme object. Read-only.
Count | Gets a Integer indicating the number of items in the ThemeColorScheme collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeColorScheme object was created. Read-only.
Parent | Gets the Parent object for the ThemeColorScheme object. Read-only.


ThemeColorScheme.Application Property (Office)

 Copy code hover
[image]

ThemeColorScheme.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ThemeColorScheme object. Read-only.

Syntax

expression .Application

expression An expression that returns a ThemeColorScheme object.

Return Value

Object

See also

Concepts

ThemeColorScheme Object

Other resources

ThemeColorScheme Object Members


ThemeColorScheme.Count Property (Office)

 Copy code hover
[image]

ThemeColorScheme.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Integer indicating the number of items in the ThemeColorScheme collection. Read-only.

Syntax

expression .Count

expression An expression that returns a ThemeColorScheme object.

Return Value

Integer

See also

Concepts

ThemeColorScheme Object

Other resources

ThemeColorScheme Object Members


ThemeColorScheme.Creator Property (Office)

 Copy code hover
[image]

ThemeColorScheme.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ThemeColorScheme object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a ThemeColorScheme object.

Return Value

Long

See also

Concepts

ThemeColorScheme Object

Other resources

ThemeColorScheme Object Members


ThemeColorScheme.Parent Property (Office)

 Copy code hover
[image]

ThemeColorScheme.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ThemeColorScheme object. Read-only.

Syntax

expression .Parent

expression An expression that returns a ThemeColorScheme object.

Return Value

Object

See also

Concepts

ThemeColorScheme Object

Other resources

ThemeColorScheme Object Members


ThemeColorScheme Methods (Office)

 Copy code hover
[image]

ThemeColorScheme Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Colors | Gets an object that represents a color in the color scheme of a Microsoft Office theme.
GetCustomColor | Gets a value that represents a color in the color scheme of a Microsoft Office theme.
Load | Loads the color scheme of a Microsoft Office theme from a file.
Save | Saves the color scheme of a Microsoft Office theme to a file.


ThemeColorScheme.Colors Method (Office)

 Copy code hover
[image]

ThemeColorScheme.Colors Method (Office)
See also Send feedback

Published: July 09, 2012

Gets an object that represents a color in the color scheme of a Microsoft Office theme.

Syntax

expression .Colors(Index)

expression An expression that returns a ThemeColorScheme object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | MsoThemeColorSchemeIndex | The index value of the ThemeColor object.

Return Value

ThemeColor

Example

In the following example, the msoThemeAccent1 theme color is set to the color Red and then the scheme is saved to a file.

VBA Copy code Copy code
Dim tTheme As OfficeTheme
Dim tcsThemeColorScheme As ThemeColorScheme
Dim tcThemeColor As ThemeColor
tcThemeColor.RGB = RGB(255, 0, 0)
Set tcColorScheme.Colors(msoThemeAccent1) = tcThemeColor
tcsThemeColorScheme.Save ("C:\myThemeColorScheme.xml")

See also

Concepts

ThemeColorScheme Object

Other resources

ThemeColorScheme Object Members


ThemeColorScheme.GetCustomColor Method (Office)

 Copy code hover
[image]

ThemeColorScheme.GetCustomColor Method (Office)
See also Send feedback

Published: July 09, 2012

Gets a value that represents a color in the color scheme of a Microsoft Office theme.

Syntax

expression .GetCustomColor(Name)

expression An expression that returns a ThemeColorScheme object.

Parameters

Name | Required/Optional | Data Type | Description
Name | Required | String | The name of the custom color.

Return Value

MsoRGBType

Remarks

If the named custom color doesn't exist, an error is generated.

Example

The following example creates a variable representing the color scheme in an Office theme and then creates another variable containing a custom color. This custom color can then be combined with other colors to define the theme.

VBA Copy code Copy code
Dim tTheme As OfficeTheme
Dim tcsThemeColorScheme As ThemeColorScheme
Dim csCustomColor As MsoRGBType
Set tcsThemeColorScheme = tTheme.ThemeColorScheme
csCustomColor = tcsThemeColorScheme.GetCustomColor("CheerfulColor")

See also

Concepts

ThemeColorScheme Object

Other resources

ThemeColorScheme Object Members


ThemeColorScheme.Load Method (Office)

 Copy code hover
[image]

ThemeColorScheme.Load Method (Office)
See also Send feedback

Published: July 09, 2012

Loads the color scheme of a Microsoft Office theme from a file.

Syntax

expression .Load(FileName)

expression An expression that returns a ThemeColorScheme object.

Parameters

Name | Required/Optional | Data Type | Description
FileName | Required | String | The name of the color theme file.

Example

The following example loads a theme color scheme from a file.

VBA Copy code Copy code
ThemeColorScheme.Load ("C:\myThemeColorScheme.xml")

See also

Concepts

ThemeColorScheme Object

Other resources

ThemeColorScheme Object Members


ThemeColorScheme.Save Method (Office)

 Copy code hover
[image]

ThemeColorScheme.Save Method (Office)
See also Send feedback

Published: July 09, 2012

Saves the color scheme of a Microsoft Office theme to a file.

Syntax

expression .Save(FileName)

expression An expression that returns a ThemeColorScheme object.

Parameters

Name | Required/Optional | Data Type | Description
FileName | Required | String | The name of the file.

Example

The following example saves the color scheme for an Office theme to a file.

VBA Copy code Copy code
ThemeColorScheme.Save("C:\myThemeColorScheme.xml")

See also

Concepts

ThemeColorScheme Object

Other resources

ThemeColorScheme Object Members


ThemeEffectScheme Object (Office)

 Copy code hover
[image]

ThemeEffectScheme Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the effects scheme of a Microsoft Office theme.

Example

The following example loads an effect scheme from a file.

VBA Copy code Copy code
Dim tesEffectScheme As ThemeEffectScheme
tesEffectScheme.Load("C:\myThemeEffectScheme.eftx")

See also

Concepts

Object Model Reference

Other resources

ThemeEffectScheme Object Members


ThemeEffectScheme Members (Office)

 Copy code hover
[image]

ThemeEffectScheme Members (Office)
Send feedback

Published: July 09, 2012

Represents the effects scheme of a Microsoft Office theme.

Methods

Name | Description
Load | Loads the effects scheme of a Microsoft Office theme from a file.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeEffectScheme object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeEffectScheme object was created. Read-only.
Parent | Gets the Parent object for the ThemeEffectScheme object. Read-only.


ThemeEffectScheme Properties (Office)

 Copy code hover
[image]

ThemeEffectScheme Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeEffectScheme object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeEffectScheme object was created. Read-only.
Parent | Gets the Parent object for the ThemeEffectScheme object. Read-only.


ThemeEffectScheme.Application Property (Office)

 Copy code hover
[image]

ThemeEffectScheme.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ThemeEffectScheme object. Read-only.

Syntax

expression .Application

expression An expression that returns a ThemeEffectScheme object.

Return Value

Object

See also

Concepts

ThemeEffectScheme Object

Other resources

ThemeEffectScheme Object Members


ThemeEffectScheme.Creator Property (Office)

 Copy code hover
[image]

ThemeEffectScheme.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ThemeEffectScheme object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a ThemeEffectScheme object.

Return Value

Long

See also

Concepts

ThemeEffectScheme Object

Other resources

ThemeEffectScheme Object Members


ThemeEffectScheme.Parent Property (Office)

 Copy code hover
[image]

ThemeEffectScheme.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ThemeEffectScheme object. Read-only.

Syntax

expression .Parent

expression An expression that returns a ThemeEffectScheme object.

Return Value

Object

See also

Concepts

ThemeEffectScheme Object

Other resources

ThemeEffectScheme Object Members


ThemeEffectScheme Methods (Office)

 Copy code hover
[image]

ThemeEffectScheme Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Load | Loads the effects scheme of a Microsoft Office theme from a file.


ThemeEffectScheme.Load Method (Office)

 Copy code hover
[image]

ThemeEffectScheme.Load Method (Office)
See also Send feedback

Published: July 09, 2012

Loads the effects scheme of a Microsoft Office theme from a file.

Syntax

expression .Load(FileName)

expression An expression that returns a ThemeEffectScheme object.

Parameters

Name | Required/Optional | Data Type | Description
FileName | Required | String | The name of the effect scheme file.

Example

The following example loads a theme effect scheme from a file.

VBA Copy code Copy code
tesEffectScheme.Load("C:\myThemeEffectScheme.eftx")

See also

Concepts

ThemeEffectScheme Object

Other resources

ThemeEffectScheme Object Members


ThemeFont Object (Office)

 Copy code hover
[image]

ThemeFont Object (Office)
See also Send feedback

Published: July 16, 2012

Represents a container for the font schemes of a Microsoft Office theme.

Example

The following example sets the Headings font scheme in a Microsoft Office theme to a Latin scheme.

VBA Copy code Copy code
Dim tTheme As OfficeTheme
Dim tfThemeFontScheme As ThemeFontScheme
Dim tfThemeFont As ThemeFont
Set tfThemeFontScheme = tTheme.ThemeFontScheme
Set tfThemeFont = tfThemeFontScheme.MajorFont(msoThemeLatin)

See also

Concepts

Object Model Reference

Other resources

ThemeFont Object Members


ThemeFont Members (Office)

 Copy code hover
[image]

ThemeFont Members (Office)
Send feedback

Published: July 09, 2012

Represents a container for the font schemes of a Microsoft Office theme.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeFont object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeFont object was created. Read-only.
Name | Gets or sets the name of a font in the font scheme of a Microsoft Office theme. Read/write.
Parent | Gets the Parent object for the ThemeFont object. Read-only.


ThemeFont Properties (Office)

 Copy code hover
[image]

ThemeFont Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeFont object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeFont object was created. Read-only.
Name | Gets or sets the name of a font in the font scheme of a Microsoft Office theme. Read/write.
Parent | Gets the Parent object for the ThemeFont object. Read-only.


ThemeFont.Application Property (Office)

 Copy code hover
[image]

ThemeFont.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ThemeFont object. Read-only.

Syntax

expression .Application

expression An expression that returns a ThemeFont object.

Return Value

Object

See also

Concepts

ThemeFont Object

Other resources

ThemeFont Object Members


ThemeFont.Creator Property (Office)

 Copy code hover
[image]

ThemeFont.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ThemeFont object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a ThemeFont object.

Return Value

Long

See also

Concepts

ThemeFont Object

Other resources

ThemeFont Object Members


ThemeFont.Name Property (Office)

 Copy code hover
[image]

ThemeFont.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the name of a font in the font scheme of a Microsoft Office theme. Read/write.

Syntax

expression .Name

expression An expression that returns a ThemeFont object.

Return Value

String

See also

Concepts

ThemeFont Object

Other resources

ThemeFont Object Members


ThemeFont.Parent Property (Office)

 Copy code hover
[image]

ThemeFont.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ThemeFont object. Read-only.

Syntax

expression .Parent

expression An expression that returns a ThemeFont object.

Return Value

Object

See also

Concepts

ThemeFont Object

Other resources

ThemeFont Object Members


ThemeFonts Object (Office)

 Copy code hover
[image]

ThemeFonts Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of major and minor fonts in the font scheme of a Microsoft Office theme.

Example

The following example sets a ThemeFonts object to a minor theme font.

VBA Copy code Copy code
Dim tTheme As OfficeTheme
Dim tfThemeFonts As ThemeFonts
Set tfThemeFonts = tTheme.ThemeFontScheme.MinorFont

See also

Concepts

Object Model Reference

Other resources

ThemeFonts Object Members


ThemeFonts Members (Office)

 Copy code hover
[image]

ThemeFonts Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of major and minor fonts in the font scheme of a Microsoft Office theme.

Methods

Name | Description
Item | Gets one of the three language fonts contained in the ThemeFonts collection.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeFonts object. Read-only.
Count | Gets a Long indicating the number of items in the ThemeFonts collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeFonts object was created. Read-only.
Parent | Gets the Parent object for the ThemeFonts object. Read-only.


ThemeFonts Properties (Office)

 Copy code hover
[image]

ThemeFonts Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeFonts object. Read-only.
Count | Gets a Long indicating the number of items in the ThemeFonts collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeFonts object was created. Read-only.
Parent | Gets the Parent object for the ThemeFonts object. Read-only.


ThemeFonts.Application Property (Office)

 Copy code hover
[image]

ThemeFonts.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ThemeFonts object. Read-only.

Syntax

expression .Application

expression An expression that returns a ThemeFonts object.

Return Value

Object

See also

Concepts

ThemeFonts Object

Other resources

ThemeFonts Object Members


ThemeFonts.Count Property (Office)

 Copy code hover
[image]

ThemeFonts.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the ThemeFonts collection. Read-only.

Syntax

expression .Count

expression An expression that returns a ThemeFonts object.

Return Value

Integer

See also

Concepts

ThemeFonts Object

Other resources

ThemeFonts Object Members


ThemeFonts.Creator Property (Office)

 Copy code hover
[image]

ThemeFonts.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ThemeFonts object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a ThemeFonts object.

Return Value

Long

See also

Concepts

ThemeFonts Object

Other resources

ThemeFonts Object Members


ThemeFonts.Parent Property (Office)

 Copy code hover
[image]

ThemeFonts.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ThemeFonts object. Read-only.

Syntax

expression .Parent

expression An expression that returns a ThemeFonts object.

Return Value

Object

See also

Concepts

ThemeFonts Object

Other resources

ThemeFonts Object Members


ThemeFonts Methods (Office)

 Copy code hover
[image]

ThemeFonts Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Item | Gets one of the three language fonts contained in the ThemeFonts collection.


ThemeFonts.Item Method (Office)

 Copy code hover
[image]

ThemeFonts.Item Method (Office)
See also Send feedback

Published: July 09, 2012

Gets one of the three language fonts contained in the ThemeFonts collection.

Syntax

expression .Item(Index)

expression An expression that returns a ThemeFonts object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | MsoFontLanguageIndex | The index value of the ThemeFont object.

Return Value

ThemeFont

Example

The following example sets the font for the body of a document to the Latin theme.

VBA Copy code Copy code
Dim tTheme As OfficeTheme
Dim tfThemeFonts As ThemeFonts
Dim latinMinorFont As ThemeFont
Set tfThemeFonts = tTheme.ThemeFontScheme.MinorFont
Set latinMinorFont = tfThemeFonts(msoThemeLatin)

See also

Concepts

ThemeFonts Object

Other resources

ThemeFonts Object Members


ThemeFontScheme Object (Office)

 Copy code hover
[image]

ThemeFontScheme Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the font scheme of a Microsoft Office theme.

Example

The following example creates an object that represents the font scheme for a Microsoft Office theme.

VBA Copy code Copy code
Dim tTheme As OfficeTheme
Dim tfsThemeFontScheme As ThemeFontScheme
Set tfsThemeFontScheme = tTheme.ThemeFontScheme

See also

Concepts

Object Model Reference

Other resources

ThemeFontScheme Object Members


ThemeFontScheme Members (Office)

 Copy code hover
[image]

ThemeFontScheme Members (Office)
Send feedback

Published: July 09, 2012

Represents the font scheme of a Microsoft Office theme.

Methods

Name | Description
Load | Loads the font scheme of a Microsoft Office theme from a file.
Save | Saves the font scheme of a Microsoft Office theme to a file.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeFontScheme object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeFontScheme object was created. Read-only.
MajorFont | Gets the font setting for the "Headings" in a document. Read-only.
MinorFont | Gets the font settings for the "Body" of a document. Read-only.
Parent | Gets the Parent object for the ThemeFontScheme object. Read-only.


ThemeFontScheme Properties (Office)

 Copy code hover
[image]

ThemeFontScheme Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the ThemeFontScheme object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the ThemeFontScheme object was created. Read-only.
MajorFont | Gets the font setting for the "Headings" in a document. Read-only.
MinorFont | Gets the font settings for the "Body" of a document. Read-only.
Parent | Gets the Parent object for the ThemeFontScheme object. Read-only.


ThemeFontScheme.Application Property (Office)

 Copy code hover
[image]

ThemeFontScheme.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the ThemeFontScheme object. Read-only.

Syntax

expression .Application

expression An expression that returns a ThemeFontScheme object.

Return Value

Object

See also

Concepts

ThemeFontScheme Object

Other resources

ThemeFontScheme Object Members


ThemeFontScheme.Creator Property (Office)

 Copy code hover
[image]

ThemeFontScheme.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the ThemeFontScheme object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a ThemeFontScheme object.

Return Value

Long

See also

Concepts

ThemeFontScheme Object

Other resources

ThemeFontScheme Object Members


ThemeFontScheme.MajorFont Property (Office)

 Copy code hover
[image]

ThemeFontScheme.MajorFont Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the font setting for the "Headings" in a document. Read-only.

Syntax

expression .MajorFont

expression An expression that returns a ThemeFontScheme object.

Return Value

ThemeFonts

See also

Concepts

ThemeFontScheme Object

Other resources

ThemeFontScheme Object Members


ThemeFontScheme.MinorFont Property (Office)

 Copy code hover
[image]

ThemeFontScheme.MinorFont Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the font settings for the "Body" of a document. Read-only.

Syntax

expression .MinorFont

expression An expression that returns a ThemeFontScheme object.

Return Value

ThemeFonts

See also

Concepts

ThemeFontScheme Object

Other resources

ThemeFontScheme Object Members


ThemeFontScheme.Parent Property (Office)

 Copy code hover
[image]

ThemeFontScheme.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the ThemeFontScheme object. Read-only.

Syntax

expression .Parent

expression An expression that returns a ThemeFontScheme object.

Return Value

Object

See also

Concepts

ThemeFontScheme Object

Other resources

ThemeFontScheme Object Members


ThemeFontScheme Methods (Office)

 Copy code hover
[image]

ThemeFontScheme Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Load | Loads the font scheme of a Microsoft Office theme from a file.
Save | Saves the font scheme of a Microsoft Office theme to a file.


ThemeFontScheme.Load Method (Office)

 Copy code hover
[image]

ThemeFontScheme.Load Method (Office)
See also Send feedback

Published: July 09, 2012

Loads the font scheme of a Microsoft Office theme from a file.

Syntax

expression .Load(FileName)

expression An expression that returns a ThemeFontScheme object.

Parameters

Name | Required/Optional | Data Type | Description
FileName | Required | String | The name of the font scheme file.

Example

The following example loads a theme font scheme from a file.

VBA Copy code Copy code
ThemeFontScheme.Load ("C:\myThemeFontScheme.xml")

See also

Concepts

ThemeFontScheme Object

Other resources

ThemeFontScheme Object Members


ThemeFontScheme.Save Method (Office)

 Copy code hover
[image]

ThemeFontScheme.Save Method (Office)
See also Send feedback

Published: July 09, 2012

Saves the font scheme of a Microsoft Office theme to a file.

Syntax

expression .Save(FileName)

expression An expression that returns a ThemeFontScheme object.

Parameters

Name | Required/Optional | Data Type | Description
FileName | Required | String | The name of the file.

Example

The following example saves the Office theme font scheme to a file.

VBA Copy code Copy code
ThemeFontScheme.Save("C:\myThemeFontScheme.xml")

See also

Concepts

ThemeFontScheme Object

Other resources

ThemeFontScheme Object Members


UserPermission Object (Office)

 Copy code hover
[image]

UserPermission Object (Office)
See also Send feedback

Published: July 09, 2012

Associates a set of permissions on the active document with a single user and an optional expiration date. Represents a member of the active document's Permission collection.

Remarks

Use the Add method of the Permission object to grant specific permissions on the active document to a new user, with an optional expiration date. Use the Remove method of the UserPermission object to remove a user and the user's permissions.

While some permissions granted through the user interface (such as msoPermissionPrint) apply to all users, you can use the UserPermission object to assign them on a per-user basis with per-user expiration dates.

Example

The following example determines whether the active document has restricted permissions, then lists users and their assigned permissions by returning the UserId, Permission, and ExpirationDate properties of each UserPermission in the document's Permission collection.

Copy code Copy code
 Dim irmPermission As Office.Permission
 Dim irmUserPerm As Office.UserPermission
 Dim strIRMInfo As String
 Set irmPermission = ActiveWorkbook.Permission
 If irmPermission.Enabled Then
 For Each irmUserPerm In irmPermission
 strIRMInfo = strIRMInfo & irmUserPerm.UserId & vbCrLf & _
 " - Permissions: " & irmUserPerm.Permission & vbCrLf & _
 " - Expiration Date: " & irmUserPerm.ExpirationDate & vbCrLf
 Next
 MsgBox strIRMInfo, _
 vbInformation + vbOKOnly, "IRM Information"
 Else
 MsgBox "This document is not restricted.", _
 vbInformation + vbOKOnly, "IRM Information"
 End If
 Set irmUserPerm = Nothing
 Set irmPermission = Nothing

See also

Concepts

Object Model Reference

Other resources

UserPermission Object Members


UserPermission Members (Office)

 Copy code hover
[image]

UserPermission Members (Office)
Send feedback

Published: July 09, 2012

Associates a set of permissions on the active document with a single user and an optional expiration date. Represents a member of the active document's Permission collection.

Methods

Name | Description
Remove | Removes the specified UserPermission object from the Permission collection of the active document.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the UserPermission object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the UserPermission object was created. Read-only.
ExpirationDate | Gets or sets the optional expiration date of the permissions on the active document assigned to the user associated with the specified UserPermission object. Read/write.
Parent | Gets the Parent object for the UserPermission object. Read-only.
Permission | Returns or sets a MsoPermission constant as a Long value representing the permissions on the active document assigned to the user associated with the specified UserPermission object. Read/write.
UserId | Gets the e-mail name of the user whose permissions on the active document are determined by the specified UserPermission object. Read-only.


UserPermission Properties (Office)

 Copy code hover
[image]

UserPermission Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the UserPermission object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the UserPermission object was created. Read-only.
ExpirationDate | Gets or sets the optional expiration date of the permissions on the active document assigned to the user associated with the specified UserPermission object. Read/write.
Parent | Gets the Parent object for the UserPermission object. Read-only.
Permission | Returns or sets a MsoPermission constant as a Long value representing the permissions on the active document assigned to the user associated with the specified UserPermission object. Read/write.
UserId | Gets the e-mail name of the user whose permissions on the active document are determined by the specified UserPermission object. Read-only.


UserPermission.Application Property (Office)

 Copy code hover
[image]

UserPermission.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the UserPermission object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a UserPermission object.

Return Value

Object

See also

Concepts

UserPermission Object

Other resources

UserPermission Object Members


UserPermission.Creator Property (Office)

 Copy code hover
[image]

UserPermission.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the UserPermission object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a UserPermission object.

Return Value

Long

See also

Concepts

UserPermission Object

Other resources

UserPermission Object Members


UserPermission.ExpirationDate Property (Office)

 Copy code hover
[image]

UserPermission.ExpirationDate Property (Office)
See also Send feedback

Published: July 09, 2012

Gets or sets the optional expiration date of the permissions on the active document assigned to the user associated with the specified UserPermission object. Read/write.

Syntax

expression .ExpirationDate

expression A variable that represents a UserPermission object.

Return Value

Variant

Remarks

The UserPermission object associates a set of permissions on the active document with a single user and an optional expiration date. The ExpirationDate property returns or sets the optional expiration date of the specified UserPermission object using the local time zone.

See also

Concepts

UserPermission Object

Other resources

UserPermission Object Members


UserPermission.Parent Property (Office)

 Copy code hover
[image]

UserPermission.Parent Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the Parent object for the UserPermission object. Read-only.

Syntax

expression .Parent

expression A variable that represents a UserPermission object.

Return Value

Object

See also

Concepts

UserPermission Object

Other resources

UserPermission Object Members


UserPermission.Permission Property (Office)

 Copy code hover
[image]

UserPermission.Permission Property (Office)
See also Send feedback

Published: July 09, 2012

Returns or sets a MsoPermission constant as a Long value representing the permissions on the active document assigned to the user associated with the specified UserPermission object. Read/write.

Syntax

expression .Permission

expression A variable that represents a UserPermission object.

Remarks

The Permission property can be one or a combination of MsoPermission constants.

The UserPermission object associates a set of permissions on the active document with a single user and an optional expiration date. The Permission property returns the set of user permissions determined by the specified UserPermission object. While some permissions granted through the user interface (such as msoPermissionPrint) apply to all users, you can use the UserPermission object to assign them on a per-user basis with per-user expiration dates.

  • The msoPermissionView or msoPermissionRead option corresponds to the Read option in the user interface.

  • The msoPermissionExtract option corresponds to the Allow users with read access to copy content option in the user interface.

  • The msoPermissionChange option corresponds to the Change option in the user interface. The msoPermissionChange option represents the sum of msoPermissionView + msoPermissionEdit + msoPermissionSave + msoPermissionExtract and allows users to view, edit, copy, and save, but not print the document.

  • The msoPermissionPrint option corresponds to the Print content option in the user interface.

  • The msoPermissionObjectModel option corresponds to the Access content programmatically option in the user interface and allows users to access the document programmatically through its object model. Users without msoPermissionObjectModel cannot use the object model to determine their own rights, since programmatic access is disabled.

Example

The following example uses the bitwise And operator with the Permission property and an msoPermission constant to determine whether the second user has permission to save the active document.

Copy code Copy code
 Dim irmPermission As Office.Permission
 Dim irmUserPerm As Office.UserPermission
 Set irmPermission = ActiveWorkbook.Permission
 Set irmUserPerm = irmPermission.Item(2)
 If irmUserPerm.Permission And Office.msoPermissionSave Then
 MsgBox "User " & irmUserPerm.UserId & _
 " has permission to save this document.", _
 vbInformation + vbOKOnly, "IRM Information"
 Else
 MsgBox "User " & irmUserPerm.UserId & _
 " does NOT have permission to save this document.", _
 vbInformation + vbOKOnly, "IRM Information"
 End If
 Set irmUserPerm = Nothing
 Set irmPermission = Nothing

See also

Concepts

UserPermission Object

Other resources

UserPermission Object Members


UserPermission.UserId Property (Office)

 Copy code hover
[image]

UserPermission.UserId Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the e-mail name of the user whose permissions on the active document are determined by the specified UserPermission object. Read-only.

Syntax

expression .UserId

expression A variable that represents a UserPermission object.

Remarks

The UserPermission object associates a set of permissions on the active document with a single user and an optional expiration date. The UserID property returns the name in e-mail form of the user whose permissions are determined by the specified UserPermission object.

Example

The following example lists the users who have permissions on the active document.

Copy code Copy code
 Dim irmPermission As Office.Permission
 Dim irmUserPerm As Office.UserPermission
 Dim strUsers As String
 Set irmPermission = ActiveWorkbook.Permission
 If irmPermission.Enabled Then
 For Each irmUserPerm In irmPermission
 strUsers = strUsers & irmUserPerm.UserId & vbCrLf
 Next
 MsgBox strUsers, _
 vbInformation + vbOKOnly, "IRM Information"
 Else
 MsgBox "Permissions are not enabled for this document.", _
 vbInformation + vbOKOnly, "IRM Information"
 End If
 Set irmUserPerm = Nothing
 Set irmPermission = Nothing

See also

Concepts

UserPermission Object

Other resources

UserPermission Object Members


UserPermission Methods (Office)

 Copy code hover
[image]

UserPermission Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Remove | Removes the specified UserPermission object from the Permission collection of the active document.


UserPermission.Remove Method (Office)

 Copy code hover
[image]

UserPermission.Remove Method (Office)
See also Send feedback

Published: July 09, 2012

Removes the specified UserPermission object from the Permission collection of the active document.

Syntax

expression .Remove

expression Required. A variable that represents a UserPermission object.

Remarks

The UserPermission object associates a set of permissions on the active document with a single user and an optional expiration date. The Remove method removes the user and the set of user permissions determined by the specified UserPermission object.

Example

The following example removes the second user's permissions on the active document from the document's Permission collection.

VBA Copy code Copy code
 Dim irmPermission As Office.Permission
 Dim irmUserPerm As Office.UserPermission
 Set irmPermission = ActiveWorkbook.Permission
 Set irmUserPerm = irmPermission.Item(2)
 irmUserPerm.Remove
 MsgBox "Permission removed.", _
 vbInformation + vbOKOnly, "IRM Information"
 Set irmUserPerm = Nothing
 Set irmPermission = Nothing

See also

Concepts

UserPermission Object

Other resources

UserPermission Object Members


WebPageFont Object (Office)

 Copy code hover
[image]

WebPageFont Object (Office)
See also Send feedback

Published: July 09, 2012

Represents the default font used when documents are saved as Web pages for a particular character set.

Remarks

Use the WebPageFont object to describe the proportional font, proportional font size, fixed-width font, and fixed-width font size for any available character set .

Example

The following example sets the proportional font and proportional font size for the WebPageFont object's "myFont".

Copy code Copy code
With myFont
 ProportionalFont = Verdana
 ProportionalFontSize = 14

See also

Concepts

Object Model Reference

Other resources

WebPageFont Object Members


WebPageFont Members (Office)

 Copy code hover
[image]

WebPageFont Members (Office)
Send feedback

Published: July 09, 2012

Represents the default font used when documents are saved as Web pages for a particular character set.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WebPageFont object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WebPageFont object was created. Read-only.
FixedWidthFont | Sets or gets the fixed-width font setting in the host application. Read/write.
FixedWidthFontSize | Sets or gets the fixed-width font size setting in the host application, in points. Read/write.
ProportionalFont | Sets or gets the proportional font setting in the host application. Read/write.
ProportionalFontSize | Sets or gets the proportional font size setting in the host application, in points. Read/write.


WebPageFont Properties (Office)

 Copy code hover
[image]

WebPageFont Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WebPageFont object (you can use this property with an Automation object to return that object's container application). Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WebPageFont object was created. Read-only.
FixedWidthFont | Sets or gets the fixed-width font setting in the host application. Read/write.
FixedWidthFontSize | Sets or gets the fixed-width font size setting in the host application, in points. Read/write.
ProportionalFont | Sets or gets the proportional font setting in the host application. Read/write.
ProportionalFontSize | Sets or gets the proportional font size setting in the host application, in points. Read/write.


WebPageFont.Application Property (Office)

 Copy code hover
[image]

WebPageFont.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the WebPageFont object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a WebPageFont object.

Return Value

Object

See also

Concepts

WebPageFont Object

Other resources

WebPageFont Object Members


WebPageFont.Creator Property (Office)

 Copy code hover
[image]

WebPageFont.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the WebPageFont object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a WebPageFont object.

Return Value

Long

See also

Concepts

WebPageFont Object

Other resources

WebPageFont Object Members


WebPageFont.FixedWidthFont Property (Office)

 Copy code hover
[image]

WebPageFont.FixedWidthFont Property (Office)
See also Send feedback

Published: July 09, 2012

Sets or gets the fixed-width font setting in the host application. Read/write.

Syntax

expression .FixedWidthFont

expression A variable that represents a WebPageFont object.

Remarks

When you set the FixedWidthFont property, the host application does not check the value for validity.

Example

This example sets the fixed-width font and fixed-width font size for the English/Western European/Other Latin Script character set in the active application.

Copy code Copy code
Application.DefaultWebOptions. _
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript) _
.FixedWidthFont = "System"
Application.DefaultWebOptions. _
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript) _
.FixedWidthFontSize = 12

See also

Concepts

WebPageFont Object

Other resources

WebPageFont Object Members


WebPageFont.FixedWidthFontSize Property (Office)

 Copy code hover
[image]

WebPageFont.FixedWidthFontSize Property (Office)
See also Send feedback

Published: July 09, 2012

Sets or gets the fixed-width font size setting in the host application, in points. Read/write.

Syntax

expression .FixedWidthFontSize

expression A variable that represents a WebPageFont object.

Remarks

When you set the FixedWidthFontSize property, the host application does not check the value for validity. If you enter an invalid value, such as a nonnumber, the host application sets the size to 0 points. You can enter half-point sizes; if you enter other fractional point sizes, they are rounded up or down to the nearest half-point.

Example

This example sets the fixed-width font and fixed-width font size for the English/Western European/Other Latin Script character set in the active application.

Copy code Copy code
Application.DefaultWebOptions. _
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript) _
.FixedWidthFont = "System"
Application.DefaultWebOptions. _
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript) _
.FixedWidthFontSize = 12

See also

Concepts

WebPageFont Object

Other resources

WebPageFont Object Members


WebPageFont.ProportionalFont Property (Office)

 Copy code hover
[image]

WebPageFont.ProportionalFont Property (Office)
See also Send feedback

Published: July 09, 2012

Sets or gets the proportional font setting in the host application. Read/write.

Syntax

expression .ProportionalFont

expression A variable that represents a WebPageFont object.

Remarks

When you set the ProportionalFont property, the host application does not check the value for validity.

Example

This example sets the proportional font and proportional font size for the English/Western European/Other Latin Script character set in the active application.

Copy code Copy code
Application.DefaultWebOptions. _
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript) _
.ProportionalFont = "Tahoma"
Application.DefaultWebOptions. _
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript) _
.ProportionalFontSize = 14.5

See also

Concepts

WebPageFont Object

Other resources

WebPageFont Object Members


WebPageFont.ProportionalFontSize Property (Office)

 Copy code hover
[image]

WebPageFont.ProportionalFontSize Property (Office)
See also Send feedback

Published: July 09, 2012

Sets or gets the proportional font size setting in the host application, in points. Read/write.

Syntax

expression .ProportionalFontSize

expression A variable that represents a WebPageFont object.

Remarks

When you set the ProportionalFontSize property, the host application does not check the value for validity. If you enter an invalid value, such as a nonnumber, the host application sets the size to 0 points. You can enter half-point sizes; if you enter other fractional point sizes, they are rounded up or down to the nearest half-point.

Example

This example sets the proportional font and proportional font size for the English/Western European/Other Latin Script character set in the active application.

Copy code Copy code
Application.DefaultWebOptions. _
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript) _
.ProportionalFont = "Tahoma"
Application.DefaultWebOptions. _
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript) _
.ProportionalFontSize = 14.5

See also

Concepts

WebPageFont Object

Other resources

WebPageFont Object Members


WebPageFonts Object (Office)

 Copy code hover
[image]

WebPageFonts Object (Office)
See also Send feedback

Published: July 09, 2012

A collection of WebPageFont objects that describe the proportional font, proportional font size, fixed-width font, and fixed-width font size used when documents are saved as Web pages. You can specify a different set of Web page font properties for each available character set.

Remarks

The WebPageFonts collection contains one WebPageFont object for each character set.

Example

The following example uses the Item property to set "myFont" to the WebPageFont object for the English/Western European/Other Latin Script character set in the current application.

Copy code Copy code
Dim myFont As WebPageFont
Set myFont = _
 Application.DefaultWebOptions.Fonts.Item_
 (msoCharacterSetEnglishWesternEuropeanOtherLatinScript)

See also

Concepts

Object Model Reference

Other resources

WebPageFonts Object Members


WebPageFonts Members (Office)

 Copy code hover
[image]

WebPageFonts Members (Office)
Send feedback

Published: July 09, 2012

A collection of WebPageFont objects that describe the proportional font, proportional font size, fixed-width font, and fixed-width font size used when documents are saved as Web pages. You can specify a different set of Web page font properties for each available character set.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WebPageFonts object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the WebPageFonts object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WebPageFonts object was created. Read-only.
Item | Gets a WebPageFont object from the WebPageFonts collection for a particular value of MsoCharacterSet. Read-only.


WebPageFonts Properties (Office)

 Copy code hover
[image]

WebPageFonts Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WebPageFonts object (you can use this property with an Automation object to return that object's container application). Read-only.
Count | Gets a Long indicating the number of items in the WebPageFonts object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WebPageFonts object was created. Read-only.
Item | Gets a WebPageFont object from the WebPageFonts collection for a particular value of MsoCharacterSet. Read-only.


WebPageFonts.Application Property (Office)

 Copy code hover
[image]

WebPageFonts.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the WebPageFonts object (you can use this property with an Automation object to return that object's container application). Read-only.

Syntax

expression .Application

expression A variable that represents a WebPageFonts object.

Return Value

Object

See also

Concepts

WebPageFonts Object

Other resources

WebPageFonts Object Members


WebPageFonts.Count Property (Office)

 Copy code hover
[image]

WebPageFonts.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the WebPageFonts object. Read-only.

Syntax

expression .Count

expression A variable that represents a WebPageFonts object.

Return Value

Long

See also

Concepts

WebPageFonts Object

Other resources

WebPageFonts Object Members


WebPageFonts.Creator Property (Office)

 Copy code hover
[image]

WebPageFonts.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the WebPageFonts object was created. Read-only.

Syntax

expression .Creator

expression A variable that represents a WebPageFonts object.

Return Value

Long

See also

Concepts

WebPageFonts Object

Other resources

WebPageFonts Object Members


WebPageFonts.Item Property (Office)

 Copy code hover
[image]

WebPageFonts.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a WebPageFont object from the WebPageFonts collection for a particular value of MsoCharacterSet. Read-only.

Syntax

expression .Item(Index)

expression Required. A variable that represents a WebPageFonts object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | MsoCharacterSet | The specified character set.

Example

The following example uses the Item property to set "myFont" to the WebPageFont object for the English/Western European/Other Latin Script character set in the active application.

VBA Copy code Copy code
Dim myFont As WebPageFont
Set myFont = _
 Application.DefaultWebOptions.Fonts. _
 Item(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)

See also

Concepts

WebPageFonts Object

Other resources

WebPageFonts Object Members


WorkflowTask Object (Office)

 Copy code hover
[image]

WorkflowTask Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a single workflow task in a WorkflowTasks collection.

Example

The following example displays the name of each workflow task in the current document and then displays the workflow task edit user interface for a specific task. It should be noted that calling the GetWorkflowTasks method involves a round-trip to the server.

VBA Copy code Copy code
Sub DisplayWorkTask()
Dim objWorkflowTasks As WorkflowTasks
Dim objWorkflowTask As WorkflowTask
Dim cnt As Integer

Set objWorkflowTasks = Document.GetWorkflowTasks()

For cnt = 1 To objWorkflowTasks.Count
 Debug.Print objWorkflowTask(cnt).Name
Next

Set objWorkflowTask = objWorkflowTasks(1)
objWorkflowTask.Show

End Sub

See also

Concepts

Object Model Reference

Other resources

WorkflowTask Object Members


WorkflowTask Members (Office)

 Copy code hover
[image]

WorkflowTask Members (Office)
Send feedback

Published: July 09, 2012

Represents a single workflow task in a WorkflowTasks collection.

Methods

Name | Description
Show | Displays a workflow task edit user interface for the specified WorkflowTask object.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WorkflowTask object. Read-only.
AssignedTo | Gets the name of the person that the workflow task is assigned to. Read-only.
CreatedBy | Gets the name of the person that created the workflow task. Read-only.
CreatedDate | Gets the date that a workflow task was created. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WorkflowTask object was created. Read-only.
Description | Gets the description of a workflow task. Read-only.
DueDate | Gets the date that a workflow task is due. Read-only.
Id | Gets the ID of the Sharepoint list item. Read-only.
ListID | Gets the ID of the list containing the workflow task. Read-only.
Name | Gets the name of the WorkflowTask object. Read-only.
WorkflowID | Gets the ID of the workflow associated with a workflow task. Read-only.


WorkflowTask Properties (Office)

 Copy code hover
[image]

WorkflowTask Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WorkflowTask object. Read-only.
AssignedTo | Gets the name of the person that the workflow task is assigned to. Read-only.
CreatedBy | Gets the name of the person that created the workflow task. Read-only.
CreatedDate | Gets the date that a workflow task was created. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WorkflowTask object was created. Read-only.
Description | Gets the description of a workflow task. Read-only.
DueDate | Gets the date that a workflow task is due. Read-only.
Id | Gets the ID of the Sharepoint list item. Read-only.
ListID | Gets the ID of the list containing the workflow task. Read-only.
Name | Gets the name of the WorkflowTask object. Read-only.
WorkflowID | Gets the ID of the workflow associated with a workflow task. Read-only.


WorkflowTask.Application Property (Office)

 Copy code hover
[image]

WorkflowTask.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the WorkflowTask object. Read-only.

Syntax

expression .Application

expression An expression that returns a WorkflowTask object.

Return Value

Object

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTask.AssignedTo Property (Office)

 Copy code hover
[image]

WorkflowTask.AssignedTo Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the person that the workflow task is assigned to. Read-only.

Syntax

expression .AssignedTo

expression An expression that returns a WorkflowTask object.

Return Value

String

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTask.CreatedBy Property (Office)

 Copy code hover
[image]

WorkflowTask.CreatedBy Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the person that created the workflow task. Read-only.

Syntax

expression .CreatedBy

expression An expression that returns a WorkflowTask object.

Return Value

String

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTask.CreatedDate Property (Office)

 Copy code hover
[image]

WorkflowTask.CreatedDate Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the date that a workflow task was created. Read-only.

Syntax

expression .CreatedDate

expression An expression that returns a WorkflowTask object.

Return Value

Date

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTask.Creator Property (Office)

 Copy code hover
[image]

WorkflowTask.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the WorkflowTask object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a WorkflowTask object.

Return Value

Long

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTask.Description Property (Office)

 Copy code hover
[image]

WorkflowTask.Description Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the description of a workflow task. Read-only.

Syntax

expression .Description

expression An expression that returns a WorkflowTask object.

Return Value

String

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTask.DueDate Property (Office)

 Copy code hover
[image]

WorkflowTask.DueDate Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the date that a workflow task is due. Read-only.

Syntax

expression .DueDate

expression An expression that returns a WorkflowTask object.

Return Value

Date

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTask.Id Property (Office)

 Copy code hover
[image]

WorkflowTask.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the ID of the Sharepoint list item. Read-only.

Syntax

expression .Id

expression An expression that returns a WorkflowTask object.

Return Value

String

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTask.ListID Property (Office)

 Copy code hover
[image]

WorkflowTask.ListID Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the ID of the list containing the workflow task. Read-only.

Syntax

expression .ListID

expression An expression that returns a WorkflowTask object.

Return Value

String

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTask.Name Property (Office)

 Copy code hover
[image]

WorkflowTask.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the WorkflowTask object. Read-only.

Syntax

expression .Name

expression An expression that returns a WorkflowTask object.

Return Value

String

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTask.WorkflowID Property (Office)

 Copy code hover
[image]

WorkflowTask.WorkflowID Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the ID of the workflow associated with a workflow task. Read-only.

Syntax

expression .WorkflowID

expression An expression that returns a WorkflowTask object.

Return Value

String

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTask Methods (Office)

 Copy code hover
[image]

WorkflowTask Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Show | Displays a workflow task edit user interface for the specified WorkflowTask object.


WorkflowTask.Show Method (Office)

 Copy code hover
[image]

WorkflowTask.Show Method (Office)
See also Send feedback

Published: July 09, 2012

Displays a workflow task edit user interface for the specified WorkflowTask object.

Syntax

expression .Show

expression An expression that returns a WorkflowTask object.

Return Value

Integer

Example

The following example displays the name of each workflow task in the current document and then displays the workflow task edit user interface for a specific task.

VBA Copy code Copy code
Sub DisplayWorkTask()
Dim objWorkflowTasks As WorkflowTasks
Dim objWorkflowTask As WorkflowTask
Dim cnt As Integer

Set objWorkflowTasks = Document.GetWorkflowTasks()

For cnt = 1 To objWorkflowTasks.Count
 Debug.Print objWorkflowTask(cnt).Name
Next

Set objWorkflowTask = objWorkflowTasks(1)
objWorkflowTask.Show

End Sub

See also

Concepts

WorkflowTask Object

Other resources

WorkflowTask Object Members


WorkflowTasks Object (Office)

 Copy code hover
[image]

WorkflowTasks Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of WorkflowTask objects.

Example

The following example displays the name of each workflow task in the current document and then displays the workflow task edit user interface for a specific task. It should be noted that calling the GetWorkflowTasks method involves a round-trip to the server.

VBA Copy code Copy code
Sub DisplayWorkTask()
Dim objWorkflowTasks As WorkflowTasks
Dim objWorkflowTask As WorkflowTask
Dim cnt As Integer

Set objWorkflowTasks = Document.GetWorkflowTasks()

For cnt = 1 To objWorkflowTasks.Count
 Debug.Print objWorkflowTask(cnt).Name
Next

Set objWorkflowTask = objWorkflowTasks(1)
objWorkflowTask.Show

End Sub

See also

Concepts

Object Model Reference

Other resources

WorkflowTasks Object Members


WorkflowTasks Members (Office)

 Copy code hover
[image]

WorkflowTasks Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of WorkflowTask objects.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WorkflowTasks object. Read-only.
Count | Gets a Long indicating the number of items in the WorkflowTasks collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WorkflowTasks object was created. Read-only.
Item | Gets a WorkflowTask object from the WorkflowTasks collection. Read-only.


WorkflowTasks Properties (Office)

 Copy code hover
[image]

WorkflowTasks Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WorkflowTasks object. Read-only.
Count | Gets a Long indicating the number of items in the WorkflowTasks collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WorkflowTasks object was created. Read-only.
Item | Gets a WorkflowTask object from the WorkflowTasks collection. Read-only.


WorkflowTasks.Application Property (Office)

 Copy code hover
[image]

WorkflowTasks.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the WorkflowTasks object. Read-only.

Syntax

expression .Application

expression An expression that returns a WorkflowTasks object.

Return Value

Object

See also

Concepts

WorkflowTasks Object

Other resources

WorkflowTasks Object Members


WorkflowTasks.Count Property (Office)

 Copy code hover
[image]

WorkflowTasks.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the WorkflowTasks collection. Read-only.

Syntax

expression .Count

expression An expression that returns a WorkflowTasks object.

Return Value

Long

See also

Concepts

WorkflowTasks Object

Other resources

WorkflowTasks Object Members


WorkflowTasks.Creator Property (Office)

 Copy code hover
[image]

WorkflowTasks.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the WorkflowTasks object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a WorkflowTasks object.

Return Value

Long

See also

Concepts

WorkflowTasks Object

Other resources

WorkflowTasks Object Members


WorkflowTasks.Item Property (Office)

 Copy code hover
[image]

WorkflowTasks.Item Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a WorkflowTask object from the WorkflowTasks collection. Read-only.

Syntax

expression .Item(Index)

expression An expression that returns a WorkflowTasks object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | The index number of the WorkflowTask object to be returned.

Return Value

WorkflowTask

See also

Concepts

WorkflowTasks Object

Other resources

WorkflowTasks Object Members


WorkflowTemplate Object (Office)

 Copy code hover
[image]

WorkflowTemplate Object (Office)
See also Send feedback

Published: July 09, 2012

Represents one of the workflows available for the current document.

Remarks

A WorkflowTemplate object corresponds to one of the options displayed in the Start New Workflow dialog box. On a Web page, the workflow templates are displayed as a list of options.

Example

The following example displays the name of each workflow template in the current document and then displays workflow specific configuration user interface for a specific template. It should be noted that calling the GetWorkflowTemplates method involves a round-trip to the server.

VBA Copy code Copy code
Sub DisplayWorkTemplates()
Dim objWorkflowTemplates As WorkflowTemplates
Dim objWorkflowTemplate As WorkflowTemplate
Dim cnt As Integer

Set objWorkflowTemplates = Document.GetWorkflowTemplates()

For cnt = 1 To objWorkflowTemplates.Count
 Debug.Print objWorkflowTemplate(cnt).Name
Next

Set objWorkflowTemplate = objWorkflowTemplates(1)
objWorkflowTemplate.Show

End Sub

See also

Concepts

Object Model Reference

Other resources

WorkflowTemplate Object Members


WorkflowTemplate Members (Office)

 Copy code hover
[image]

WorkflowTemplate Members (Office)
Send feedback

Published: July 09, 2012

Represents one of the workflows available for the current document.

Methods

Name | Description
Show | Displays a workflow specific configuration user interface for the specified WorkflowTemplate object.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WorkflowTemplate object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WorkflowTemplate object was created. Read-only.
Description | Gets the description of a workflow template. Read-only.
DocumentLibraryName | Gets the name of the document library associated with the workflow template. Read-only.
DocumentLibraryURL | Gets the URL address of the document library where workflow templates are stored. Read-only.
Id | Gets the ID of a template used to create a workflow instance. Read-only.
Name | Gets the name of the WorkflowTemplate object. Read-only.


WorkflowTemplate Properties (Office)

 Copy code hover
[image]

WorkflowTemplate Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WorkflowTemplate object. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WorkflowTemplate object was created. Read-only.
Description | Gets the description of a workflow template. Read-only.
DocumentLibraryName | Gets the name of the document library associated with the workflow template. Read-only.
DocumentLibraryURL | Gets the URL address of the document library where workflow templates are stored. Read-only.
Id | Gets the ID of a template used to create a workflow instance. Read-only.
Name | Gets the name of the WorkflowTemplate object. Read-only.


WorkflowTemplate.Application Property (Office)

 Copy code hover
[image]

WorkflowTemplate.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the WorkflowTemplate object. Read-only.

Syntax

expression .Application

expression An expression that returns a WorkflowTemplate object.

Return Value

Object

See also

Concepts

WorkflowTemplate Object

Other resources

WorkflowTemplate Object Members


WorkflowTemplate.Creator Property (Office)

 Copy code hover
[image]

WorkflowTemplate.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the WorkflowTemplate object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a WorkflowTemplate object.

Return Value

Long

See also

Concepts

WorkflowTemplate Object

Other resources

WorkflowTemplate Object Members


WorkflowTemplate.Description Property (Office)

 Copy code hover
[image]

WorkflowTemplate.Description Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the description of a workflow template. Read-only.

Syntax

expression .Description

expression An expression that returns a WorkflowTemplate object.

Return Value

String

See also

Concepts

WorkflowTemplate Object

Other resources

WorkflowTemplate Object Members


WorkflowTemplate.DocumentLibraryName Property (Office)

 Copy code hover
[image]

WorkflowTemplate.DocumentLibraryName Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the document library associated with the workflow template. Read-only.

Syntax

expression .DocumentLibraryName

expression An expression that returns a WorkflowTemplate object.

Return Value

String

See also

Concepts

WorkflowTemplate Object

Other resources

WorkflowTemplate Object Members


WorkflowTemplate.DocumentLibraryURL Property (Office)

 Copy code hover
[image]

WorkflowTemplate.DocumentLibraryURL Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the URL address of the document library where workflow templates are stored. Read-only.

Syntax

expression .DocumentLibraryURL

expression An expression that returns a WorkflowTemplate object.

Return Value

String

See also

Concepts

WorkflowTemplate Object

Other resources

WorkflowTemplate Object Members


WorkflowTemplate.Id Property (Office)

 Copy code hover
[image]

WorkflowTemplate.Id Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the ID of a template used to create a workflow instance. Read-only.

Syntax

expression .Id

expression An expression that returns a WorkflowTemplate object.

Return Value

String

See also

Concepts

WorkflowTemplate Object

Other resources

WorkflowTemplate Object Members


WorkflowTemplate.Name Property (Office)

 Copy code hover
[image]

WorkflowTemplate.Name Property (Office)
See also Send feedback

Published: July 09, 2012

Gets the name of the WorkflowTemplate object. Read-only.

Syntax

expression .Name

expression An expression that returns a WorkflowTemplate object.

Return Value

String

See also

Concepts

WorkflowTemplate Object

Other resources

WorkflowTemplate Object Members


WorkflowTemplate Methods (Office)

 Copy code hover
[image]

WorkflowTemplate Methods (Office)
Send feedback

Published: July 09, 2012

This object has the following methods:

Methods

Name | Description
Show | Displays a workflow specific configuration user interface for the specified WorkflowTemplate object.


WorkflowTemplate.Show Method (Office)

 Copy code hover
[image]

WorkflowTemplate.Show Method (Office)
See also Send feedback

Published: July 09, 2012

Displays a workflow specific configuration user interface for the specified WorkflowTemplate object.

Syntax

expression .Show

expression An expression that returns a WorkflowTemplate object.

Return Value

Integer

Example

The following example displays the name of each workflow template in the current document and then displays workflow specific configuration user interface for a specific template.

VBA Copy code Copy code
Sub DisplayWorkTemplates()
Dim objWorkflowTemplates As WorkflowTemplates
Dim objWorkflowTemplate As WorkflowTemplate
Dim cnt As Integer

Set objWorkflowTemplates = Document.GetWorkflowTemplates()

For cnt = 1 To objWorkflowTemplates.Count
 Debug.Print objWorkflowTemplate(cnt).Name
Next

Set objWorkflowTemplate = objWorkflowTemplates(1)
objWorkflowTemplate.Show

End Sub

See also

Concepts

WorkflowTemplate Object

Other resources

WorkflowTemplate Object Members


WorkflowTemplates Object (Office)

 Copy code hover
[image]

WorkflowTemplates Object (Office)
See also Send feedback

Published: July 09, 2012

Represents a collection of WorkflowTemplate objects.

Example

The following example displays the name of each workflow template in the current document and then displays workflow specific configuration user interface for a specific template. It should be noted that calling the GetWorkflowTemplates method involves a round-trip to the server.

VBA Copy code Copy code
Sub DisplayWorkTemplates()
Dim objWorkflowTemplates As WorkflowTemplates
Dim objWorkflowTemplate As WorkflowTemplate
Dim cnt As Integer

Set objWorkflowTemplates = Document.GetWorkflowTemplates()

For cnt = 1 To objWorkflowTemplates.Count
 Debug.Print objWorkflowTemplate(cnt).Name
Next

Set objWorkflowTemplate = objWorkflowTemplates(1)
objWorkflowTemplate.Show

End Sub

See also

Concepts

Object Model Reference

Other resources

WorkflowTemplates Object Members


WorkflowTemplates Members (Office)

 Copy code hover
[image]

WorkflowTemplates Members (Office)
Send feedback

Published: July 09, 2012

Represents a collection of WorkflowTemplate objects.

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WorkflowTemplates object. Read-only.
Count | Gets a Long indicating the number of items in the WorkflowTemplates collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WorkflowTemplates object was created. Read-only.
Item |


WorkflowTemplates Properties (Office)

 Copy code hover
[image]

WorkflowTemplates Properties (Office)
Send feedback

Published: July 09, 2012

This object has the following properties:

Properties

Name | Description
Application | Gets an Application object that represents the container application for the WorkflowTemplates object. Read-only.
Count | Gets a Long indicating the number of items in the WorkflowTemplates collection. Read-only.
Creator | Gets a 32-bit integer that indicates the application in which the WorkflowTemplates object was created. Read-only.
Item |


WorkflowTemplates.Application Property (Office)

 Copy code hover
[image]

WorkflowTemplates.Application Property (Office)
See also Send feedback

Published: July 09, 2012

Gets an Application object that represents the container application for the WorkflowTemplates object. Read-only.

Syntax

expression .Application

expression An expression that returns a WorkflowTemplates object.

Return Value

Object

See also

Concepts

WorkflowTemplates Object

Other resources

WorkflowTemplates Object Members


WorkflowTemplates.Count Property (Office)

 Copy code hover
[image]

WorkflowTemplates.Count Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a Long indicating the number of items in the WorkflowTemplates collection. Read-only.

Syntax

expression .Count

expression An expression that returns a WorkflowTemplates object.

Return Value

Long

See also

Concepts

WorkflowTemplates Object

Other resources

WorkflowTemplates Object Members


WorkflowTemplates.Creator Property (Office)

 Copy code hover
[image]

WorkflowTemplates.Creator Property (Office)
See also Send feedback

Published: July 09, 2012

Gets a 32-bit integer that indicates the application in which the WorkflowTemplates object was created. Read-only.

Syntax

expression .Creator

expression An expression that returns a WorkflowTemplates object.

Return Value

Long

See also

Concepts

WorkflowTemplates Object

Other resources

WorkflowTemplates Object Members


WorkflowTemplate.Item Property (Office)

 Copy code hover
[image]

WorkflowTemplate.Item Property (Office)
Send feedback

Published: July 09, 2012

Gets a WorkflowTemplate object from the WorkflowTemplates collection. Read-only.

Syntax

expression .Item(Index)

expression An expression that returns a WorkflowTemplates object.

Parameters

Name | Required/Optional | Data Type | Description
Index | Required | Long | The index number of the WorkflowTemplate object to be returned.

Return Value

WorkflowTemplate


Enumerations (Office)

 Copy code hover
[image]

Enumerations (Office)
Send feedback

Published: July 09, 2012

This section contains documentation for the enumerations in the Office object model.


BackstageGroupStyle Enumeration (Office)

 Copy code hover
[image]

BackstageGroupStyle Enumeration (Office)
Send feedback

Published: June 15, 2012

Specifies constants that define the styles of the groups on the File tab.

Name | Value | Description
BackstageGroupStyleError | 2 | Error style.
BackstageGroupStyleNormal | 0 | Normal style.
BackstageGroupStyleWarning | 1 | Warning style.


CertificateDetail Enumeration (Office)

 Copy code hover
[image]

CertificateDetail Enumeration (Office)
Send feedback

Published: June 15, 2012

Provides information about the digital certificate.

Name | Value | Description
certdetAvailable | 0 | Specifies that the digital certificate is available for signing.
certdetExpirationDate | 3 | The expiration date of the certificate.
certdetIssuer | 2 | The issuing authority of the certification.
certdetSubject | 1 | The holder of a Private Key corresponding to a Public Key.
certdetThumbprint | 4 | A hash of the certificate's complete contents.


CertificateVerificationResults Enumeration (Office)

 Copy code hover
[image]

CertificateVerificationResults Enumeration (Office)
Send feedback

Published: June 15, 2012

Provides the results of verifying a digital certificate.

Name | Value | Description
certverresError | 0 | The verification resulted in an error.
certverresExpired | 5 | The certification has expired.
certverresInvalid | 4 | The certification is invalid.
certverresRevoked | 6 | The certification has been revoked.
certverresUntrusted | 7 | The certification is from an untrusted source.
certverresUnverified | 2 | The certification is currently unverified.
certverresValid | 3 | The certification is valid.
certverresVerifying | 1 | The certificate is currently being verified.


ContentVerificationResults Enumeration (Office)

 Copy code hover
[image]

ContentVerificationResults Enumeration (Office)
Send feedback

Published: July 09, 2012

Provides the status of verifying whether the content of a document has changed.

Name | Value | Description
contverresError | 0 | The verification resulted in an error.
contverresModified | 4 | The content of the document has been modified since it was digitally signed.
contverresUnverified | 2 | The document has not been verified.
contverresValid | 3 | The content of the has been verified and is valid.
contverresVerifying | 1 | The content of the document is currently being verified.


EncryptionCipherMode Enumeration (Office)

 Copy code hover
[image]

EncryptionCipherMode Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the mode for encryption ciphers.

Name | Value | Description
cipherModeECB | 0 | ECB cipher mode.
cipherModeCBC | 1 | CBC cipher mode.


EncryptionProviderDetail Enumeration (Office)

 Copy code hover
[image]

EncryptionProviderDetail Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies details about encryption providers.

Name | Value | Description
encprovdetURL | 0 | A URL encryption provider.
encprovdetAlgorithm | 1 | An algorithm encryption provider.
encprovdetBlockCipher | 2 | A block cipher encryption provider.
encprovdetCipherBlockSize | 3 | A cipher block size encryption provider.
encprovdetCipherMode | 4 | A cipher mode encryption provider.


MailFormat Enumeration (Office)

 Copy code hover
[image]

MailFormat Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies how the body of the e-mail is displayed.

Name | Value | Description
mfHTML | 2 | The e-mail is displayed as Hyper Text Markup Language (HTML).
mfPlainText | 1 | The e-mail is displayed as plain text.
mfRTF | 3 | The e-mail is displayed as Rich Text Format (RTF).


MsoAlertButtonType Enumeration (Office)

 Copy code hover
[image]

MsoAlertButtonType Enumeration (Office)
Send feedback

This object or member is deprecated and is not intended to be used in your code.


MsoAlertCancelType Enumeration (Office)

 Copy code hover
[image]

MsoAlertCancelType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies behavior when the user cancels an alert. Only msoAlertCancelDefault is currently supported.

Name | Value | Description
msoAlertCancelDefault | -1 | Default behavior for canceling an alert.
msoAlertCancelFifth | 4 | Not supported.
msoAlertCancelFirst | 0 | Not supported.
msoAlertCancelFourth | 3 | Not supported.
msoAlertCancelSecond | 1 | Not supported.
msoAlertCancelThird | 2 | Not supported.


MsoAlertDefaultType Enumeration (Office)

 Copy code hover
[image]

MsoAlertDefaultType Enumeration (Office)
Send feedback

This object or member is deprecated and is not intended to be used in your code.


MsoAlertIconType Enumeration (Office)

 Copy code hover
[image]

MsoAlertIconType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies which icon, if any, to display with an alert.

Name | Value | Description
msoAlertIconCritical | 1 | Displays the Critical icon.
msoAlertIconInfo | 4 | Displays the Info icon.
msoAlertIconNoIcon | 0 | Displays no icon with the alert message.
msoAlertIconQuery | 2 | Displays the Query icon.
msoAlertIconWarning | 3 | Displays the Warning icon.


MsoAlignCmd Enumeration (Office)

 Copy code hover
[image]

MsoAlignCmd Enumeration (Office)
Send feedback

Published: July 09, 2012

Defines how to align specified objects relative to one another.

Name | Value | Description
msoAlignBottoms | 5 | Align bottoms of specified objects.
msoAlignCenters | 1 | Align centers of specified objects.
msoAlignLefts | 0 | Align left sides of specified objects.
msoAlignMiddles | 4 | Align middles of specified objects.
msoAlignRights | 2 | Align right sides of specified objects.
msoAlignTops | 3 | Align tops of specified objects.


MsoAnimationType Enumeration (Office)

 Copy code hover
[image]

MsoAnimationType Enumeration (Office)
Send feedback

This object or member is deprecated and is not intended to be used in your code.


MsoAppLanguageID Enumeration (Office)

 Copy code hover
[image]

MsoAppLanguageID Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies a language setting in a Microsoft Office application. The msoAppLanguageID enumeration is used with the LanguageSettings member of the Application object to determine the language used for the install language, the user interface language, or the Help language.

Name | Value | Description
msoLanguageIDExeMode | 4 | Execution mode language.
msoLanguageIDHelp | 3 | Help language.
msoLanguageIDInstall | 1 | Install language.
msoLanguageIDUI | 2 | User interface language.
msoLanguageIDUIPrevious | 5 | User interface language used prior to the current user interface language.


MsoArrowheadLength Enumeration (Office)

 Copy code hover
[image]

MsoArrowheadLength Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the length of the arrowhead at the end of a line.

Name | Value | Description
msoArrowheadLengthMedium | 2 | Medium.
msoArrowheadLengthMixed | -2 | Return value only; indicates a combination of the other states in the specified shape range.
msoArrowheadLong | 3 | Long.
msoArrowheadShort | 1 | Short.


MsoArrowheadStyle Enumeration (Office)

 Copy code hover
[image]

MsoArrowheadStyle Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the style of the arrowhead at the end of a line.

Name | Value | Description
msoArrowheadDiamond | 5 | Diamond-shaped.
msoArrowheadNone | 1 | No arrowhead.
msoArrowheadOpen | 3 | Open.
msoArrowheadOval | 6 | Oval-shaped.
msoArrowheadStealth | 4 | Stealth-shaped.
msoArrowheadStyleMixed | -2 | Return value only; indicates a combination of the other states.
msoArrowheadTriangle | 2 | Triangular.


MsoArrowheadWidth Enumeration (Office)

 Copy code hover
[image]

MsoArrowheadWidth Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the width of the arrowhead at the end of a line.

Name | Value | Description
msoArrowheadNarrow | 1 | Narrow.
msoArrowheadWide | 3 | Wide.
msoArrowheadWidthMedium | 2 | Medium.
msoArrowheadWidthMixed | -2 | Return value only; indicates a combination of the other states.


MsoAutomationSecurity Enumeration (Office)

 Copy code hover
[image]

MsoAutomationSecurity Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the security mode an application uses when programmatically opening files.

Name | Value | Description
msoAutomationSecurityByUI | 2 | Uses the security setting specified in the Security dialog box.
msoAutomationSecurityForceDisable | 3 | Disables all macros in all files opened programmatically, without showing any security alerts.
msoAutomationSecurityLow | 1 | Enables all macros. This is the default value when the application is started.


MsoAutoShapeType Enumeration (Office)

 Copy code hover
[image]

MsoAutoShapeType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the shape type for an AutoShape object.

Name | Value | Description
msoShape10pointStar | 149 | 10-point star.
msoShape12pointStar | 150 | 12-point star.
msoShape16pointStar | 94 | 16-point star.
msoShape24pointStar | 95 | 24-point star.
msoShape32pointStar | 96 | 32-point star.
msoShape4pointStar | 91 | 4-point star.
msoShape5pointStar | 92 | 5-point star.
msoShape6pointStar | 147 | 6-point star.
msoShape7pointStar | 148 | 7-point star.
msoShape8pointStar | 93 | 8-point star.
msoShapeActionButtonBackorPrevious | 129 | Back or Previous button. Supports mouse-click and mouse-over actions.
msoShapeActionButtonBeginning | 131 | Beginning button. Supports mouse-click and mouse-over actions.
msoShapeActionButtonCustom | 125 | Button with no default picture or text. Supports mouse-click and mouse-over actions.
msoShapeActionButtonDocument | 134 | Document button. Supports mouse-click and mouse-over actions.
msoShapeActionButtonEnd | 132 | End button. Supports mouse-click and mouse-over actions.
msoShapeActionButtonForwardorNext | 130 | Forward or Next button. Supports mouse-click and mouse-over actions.
msoShapeActionButtonHelp | 127 | Help button. Supports mouse-click and mouse-over actions.
msoShapeActionButtonHome | 126 | Home button. Supports mouse-click and mouse-over actions.
msoShapeActionButtonInformation | 128 | Information button. Supports mouse-click and mouse-over actions.
msoShapeActionButtonMovie | 136 | Movie button. Supports mouse-click and mouse-over actions.
msoShapeActionButtonReturn | 133 | Return button. Supports mouse-click and mouse-over actions.
msoShapeActionButtonSound | 135 | Sound button. Supports mouse-click and mouse-over actions.
msoShapeArc | 25 | Arc.
msoShapeBalloon | 137 | Balloon.
msoShapeBentArrow | 41 | Block arrow that follows a curved 90-degree angle.
msoShapeBentUpArrow | 44 | Block arrow that follows a sharp 90-degree angle. Points up by default.
msoShapeBevel | 15 | Bevel.
msoShapeBlockArc | 20 | Block arc.
msoShapeCan | 13 | Can.
msoShapeChartPlus | 182 | Square divided vertically and horizontally into four quarters.
msoShapeChartStar | 181 | Square divided six parts along vertical and diagonal lines.
msoShapeChartX | 180 | Square divided into four parts along diagonal lines.
msoShapeChevron | 52 | Chevron.
msoShapeChord | 161 | Circle with a line connecting two points on the perimeter through the interior of the circle; a circle with a chord.
msoShapeCircularArrow | 60 | Block arrow that follows a curved 180-degree angle.
msoShapeCloud | 179 | Cloud shape.
msoShapeCloudCallout | 108 | Cloud callout.
msoShapeCorner | 162 | Rectangle with rectangular-shaped hole.
msoShapeCornerTabs | 169 | Four right triangles aligning along a rectangular path; four 'snipped' corners.
msoShapeCross | 11 | Cross.
msoShapeCube | 14 | Cube.
msoShapeCurvedDownArrow | 48 | Block arrow that curves down.
msoShapeCurvedDownRibbon | 100 | Ribbon banner that curves down.
msoShapeCurvedLeftArrow | 46 | Block arrow that curves left.
msoShapeCurvedRightArrow | 45 | Block arrow that curves right.
msoShapeCurvedUpArrow | 47 | Block arrow that curves up.
msoShapeCurvedUpRibbon | 99 | Ribbon banner that curves up.
msoShapeDecagon | 144 | Decagon.
msoShapeDiagonalStripe | 141 | Rectangle with two triangles-shapes removed; a diagonal stripe.
msoShapeDiamond | 4 | Diamond.
msoShapeDodecagon | 146 | Dodecagon
msoShapeDonut | 18 | Donut.
msoShapeDoubleBrace | 27 | Double brace.
msoShapeDoubleBracket | 26 | Double bracket.
msoShapeDoubleWave | 104 | Double wave.
msoShapeDownArrow | 36 | Block arrow that points down.
msoShapeDownArrowCallout | 56 | Callout with arrow that points down.
msoShapeDownRibbon | 98 | Ribbon banner with center area below ribbon ends.
msoShapeExplosion1 | 89 | Explosion.
msoShapeExplosion2 | 90 | Explosion.
msoShapeFlowchartAlternateProcess | 62 | Alternate process flowchart symbol.
msoShapeFlowchartCard | 75 | Card flowchart symbol.
msoShapeFlowchartCollate | 79 | Collate flowchart symbol.
msoShapeFlowchartConnector | 73 | Connector flowchart symbol.
msoShapeFlowchartData | 64 | Data flowchart symbol.
msoShapeFlowchartDecision | 63 | Decision flowchart symbol.
msoShapeFlowchartDelay | 84 | Delay flowchart symbol.
msoShapeFlowchartDirectAccessStorage | 87 | Direct access storage flowchart symbol.
msoShapeFlowchartDisplay | 88 | Display flowchart symbol.
msoShapeFlowchartDocument | 67 | Document flowchart symbol.
msoShapeFlowchartExtract | 81 | Extract flowchart symbol.
msoShapeFlowchartInternalStorage | 66 | Internal storage flowchart symbol.
msoShapeFlowchartMagneticDisk | 86 | Magnetic disk flowchart symbol.
msoShapeFlowchartManualInput | 71 | Manual input flowchart symbol.
msoShapeFlowchartManualOperation | 72 | Manual operation flowchart symbol.
msoShapeFlowchartMerge | 82 | Merge flowchart symbol.
msoShapeFlowchartMultidocument | 68 | Multi-document flowchart symbol.
msoShapeFlowchartOfflineStorage | 139 | Offline storage flowchart symbol.
msoShapeFlowchartOffpageConnector | 74 | Off-page connector flowchart symbol.
msoShapeFlowchartOr | 78 | "Or" flowchart symbol.
msoShapeFlowchartPredefinedProcess | 65 | Predefined process flowchart symbol.
msoShapeFlowchartPreparation | 70 | Preparation flowchart symbol.
msoShapeFlowchartProcess | 61 | Process flowchart symbol.
msoShapeFlowchartPunchedTape | 76 | Punched tape flowchart symbol.
msoShapeFlowchartSequentialAccessStorage | 85 | Sequential access storage flowchart symbol.
msoShapeFlowchartSort | 80 | Sort flowchart symbol.
msoShapeFlowchartStoredData | 83 | Stored data flowchart symbol.
msoShapeFlowchartSummingJunction | 77 | Summing junction flowchart symbol.
msoShapeFlowchartTerminator | 69 | Terminator flowchart symbol.
msoShapeFoldedCorner | 16 | Folded corner.
msoShapeFrame | 158 | Rectangular picture frame.
msoShapeFunnel | 174 | Funnel.
msoShapeGear6 | 172 | Gear with six teeth.
msoShapeGear9 | 173 | Gear with nine teeth
msoShapeHalfFrame | 159 | Half of a rectangular picture frame.
msoShapeHeart | 21 | Heart.
msoShapeHeptagon | 145 | Heptagon.
msoShapeHexagon | 10 | Hexagon.
msoShapeHorizontalScroll | 102 | Horizontal scroll.
msoShapeIsoscelesTriangle | 7 | Isosceles triangle.
msoShapeLeftArrow | 34 | Block arrow that points left.
msoShapeLeftArrowCallout | 54 | Callout with arrow that points left.
msoShapeLeftBrace | 31 | Left brace.
msoShapeLeftBracket | 29 | Left bracket.
msoShapeLeftCircularArrow | 176 | Circular arrow pointing counter-clockwise.
msoShapeLeftRightArrow | 37 | Block arrow with arrowheads that point both left and right.
msoShapeLeftRightArrowCallout | 57 | Callout with arrowheads that point both left and right.
msoShapeLeftRightCircularArrow | 177 | Circular arrow pointing clockwise and counter-clockwise; a curved arrow with points at both ends.
msoShapeLeftRightRibbon | 140 | Ribbon with an arrow at both ends.
msoShapeLeftRightUpArrow | 40 | Block arrow with arrowheads that point left, right, and up.
msoShapeLeftUpArrow | 43 | Block arrow with arrowheads that point left and up.
msoShapeLightningBolt | 22 | Lightning bolt.
msoShapeLineCallout1 | 109 | Callout with border and horizontal callout line.
msoShapeLineCallout1AccentBar | 113 | Callout with horizontal accent bar.
msoShapeLineCallout1BorderandAccentBar | 121 | Callout with border and horizontal accent bar.
msoShapeLineCallout1NoBorder | 117 | Callout with horizontal line.
msoShapeLineCallout2 | 110 | Callout with diagonal straight line.
msoShapeLineCallout2AccentBar | 114 | Callout with diagonal callout line and accent bar.
msoShapeLineCallout2BorderandAccentBar | 122 | Callout with border, diagonal straight line, and accent bar.
msoShapeLineCallout2NoBorder | 118 | Callout with no border and diagonal callout line.
msoShapeLineCallout3 | 111 | Callout with angled line.
msoShapeLineCallout3AccentBar | 115 | Callout with angled callout line and accent bar.
msoShapeLineCallout3BorderandAccentBar | 123 | Callout with border, angled callout line, and accent bar.
msoShapeLineCallout3NoBorder | 119 | Callout with no border and angled callout line.
msoShapeLineCallout4 | 112 | Callout with callout line segments forming a U-shape.
msoShapeLineCallout4AccentBar | 116 | Callout with accent bar and callout line segments forming a U-shape.
msoShapeLineCallout4BorderandAccentBar | 124 | Callout with border, accent bar, and callout line segments forming a U-shape.
msoShapeLineCallout4NoBorder | 120 | Callout with no border and callout line segments forming a U-shape.
msoShapeLineInverse | 183 | Line inverse.
msoShapeMathDivide | 166 | Division symbol '÷'.
msoShapeMathEqual | 167 | Equivalence symbol '='.
msoShapeMathMinus | 164 | Subtraction symbol '-'.
msoShapeMathMultiply | 165 | Multiplication symbol 'x'.
msoShapeMathNotEqual | 168 | Non-equivalence symbol '≠'.
msoShapeMathPlus | 163 | Addition symbol '+'.
msoShapeMixed | -2 | Return value only; indicates a combination of the other states.
msoShapeMoon | 24 | Moon.
msoShapeNonIsoscelesTrapezoid | 143 | Trapezoid with asymmetrical non-parallel sides.
msoShapeNoSymbol | 19 | "No" symbol.
msoShapeNotchedRightArrow | 50 | Notched block arrow that points right.
msoShapeNotPrimitive | 138 | Not supported.
msoShapeOctagon | 6 | Octagon.
msoShapeOval | 9 | Oval.
msoShapeOvalCallout | 107 | Oval-shaped callout.
msoShapeParallelogram | 2 | Parallelogram.
msoShapePentagon | 51 | Pentagon.
msoShapePie | 142 | Circle ('pie') with a portion missing.
msoShapePieWedge | 175 | Quarter of a circular shape.
msoShapePlaque | 28 | Plaque.
msoShapePlaqueTabs | 171 | Four quarter-circles defining a rectangular shape.
msoShapeQuadArrow | 39 | Block arrows that point up, down, left, and right.
msoShapeQuadArrowCallout | 59 | Callout with arrows that point up, down, left, and right.
msoShapeRectangle | 1 | Rectangle.
msoShapeRectangularCallout | 105 | Rectangular callout.
msoShapeRegularPentagon | 12 | Pentagon.
msoShapeRightArrow | 33 | Block arrow that points right.
msoShapeRightArrowCallout | 53 | Callout with arrow that points right.
msoShapeRightBrace | 32 | Right brace.
msoShapeRightBracket | 30 | Right bracket.
msoShapeRightTriangle | 8 | Right triangle.
msoShapeRound1Rectangle | 151 | Rectangle with one rounded corner.
msoShapeRound2DiagRectangle | 157 | Rectangle with two rounded corners, diagonally-opposed.
msoShapeRound2SameRectangle | 152 | Rectangle with two-rounded corners that share a side.
msoShapeRoundedRectangle | 5 | Rounded rectangle.
msoShapeRoundedRectangularCallout | 106 | Rounded rectangle-shaped callout.
msoShapeSmileyFace | 17 | Smiley face.
msoShapeSnip1Rectangle | 155 | Rectangle with one snipped corner.
msoShapeSnip2DiagRectangle | 157 | Rectangle with two snipped corners, diagonally-opposed.
msoShapeSnip2SameRectangle | 156 | Rectangle with two snipped corners that share a side.
msoShapeSnipRoundRectangle | 154 | Rectangle with one snipped corner and one rounded corner.
msoShapeSquareTabs | 170 | Four small squares that define a rectangular shape.
msoShapeStripedRightArrow | 49 | Block arrow that points right with stripes at the tail.
msoShapeSun | 23 | Sun.
msoShapeSwooshArrow | 178 | Curved arrow.
msoShapeTear | 160 | Water droplet.
msoShapeTrapezoid | 3 | Trapezoid.
msoShapeUpArrow | 35 | Block arrow that points up.
msoShapeUpArrowCallout | 55 | Callout with arrow that points up.
msoShapeUpDownArrow | 38 | Block arrow that points up and down.
msoShapeUpDownArrowCallout | 58 | Callout with arrows that point up and down.
msoShapeUpRibbon | 97 | Ribbon banner with center area above ribbon ends.
msoShapeUTurnArrow | 42 | Block arrow forming a U shape.
msoShapeVerticalScroll | 101 | Vertical scroll.
msoShapeWave | 103 | Wave.


MsoAutoSize Enumeration (Office)

 Copy code hover
[image]

MsoAutoSize Enumeration (Office)
Send feedback

Published: July 09, 2012

Determines the type of automatic sizing allowed.

Name | Value | Description
msoAutoSizeMixed | -2 | A combination of automatic sizing schemes are used.
msoAutoSizeNone | 0 | No autosizing.
msoAutoSizeShapeToFitText | 1 | The shape is adjusted to fit the text.
msoAutoSizeTextToFitShape | 2 | The text is adjusted to fit the shape.


MsoBackgroundStyleIndex Enumeration (Office)

 Copy code hover
[image]

MsoBackgroundStyleIndex Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the background style for an object.

Name | Value | Description
msoBackgroundStyle1 | 1 | Specifies Style1.
msoBackgroundStyle10 | 10 | Specifies Style10.
msoBackgroundStyle11 | 11 | Specifies Style11.
msoBackgroundStyle12 | 12 | Specifies Style12.
msoBackgroundStyle2 | 2 | Specifies Style2.
msoBackgroundStyle3 | 3 | Specifies Style3.
msoBackgroundStyle4 | 4 | Specifies Style4.
msoBackgroundStyle5 | 5 | Specifies Style5.
msoBackgroundStyle6 | 6 | Specifies Style6.
msoBackgroundStyle7 | 7 | Specifies Style7.
msoBackgroundStyle8 | 8 | Specifies Style8.
msoBackgroundStyle9 | 9 | Specifies Style9.
msoBackgroundStyleMixed | -2 | Specifies a combination of styles.
msoBackgroundStyleNone | 0 | Specifies no styles.


MsoBalloonButtonType Enumeration (Office)

 Copy code hover
[image]

MsoBalloonButtonType Enumeration (Office)
Send feedback

This object or member is deprecated and is not intended to be used in your code.


MsoBalloonErrorType Enumeration (Office)

 Copy code hover
[image]

MsoBalloonErrorType Enumeration (Office)
Send feedback

This object or member is deprecated and is not intended to be used in your code.


MsoBalloonType Enumeration (Office)

 Copy code hover
[image]

MsoBalloonType Enumeration (Office)
Send feedback

This object or member is deprecated and is not intended to be used in your code.


MsoBarPosition Enumeration (Office)

 Copy code hover
[image]

MsoBarPosition Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the position or behavior of a command bar.

Name | Value | Description
msoBarBottom | 3 | Command bar is docked at the bottom of the application window.
msoBarFloating | 4 | Command bar floats on top of the application window.
msoBarLeft | 0 | Command bar is docked on the left side of the application window.
msoBarMenuBar | 6 | Command bar will be a menu bar (Macintosh only).
msoBarPopup | 5 | Command bar will be a shortcut menu.
msoBarRight | 2 | Command bar is docked on the right side of the application window.
msoBarTop | 1 | Command bar is docked at the top of the application window.


MsoBarProtection Enumeration (Office)

 Copy code hover
[image]

MsoBarProtection Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies how a command bar is protected from user customization.

Name | Value | Description
msoBarNoChangeDock | 16 | Docking setting cannot be changed.
msoBarNoChangeVisible | 8 | Command bar cannot be hidden.
msoBarNoCustomize | 1 | Command bar cannot be customized.
msoBarNoHorizontalDock | 64 | Command bar cannot be docked to the top or bottom.
msoBarNoMove | 4 | Command bar cannot be moved.
msoBarNoProtection | 0 | All aspects of command bar can be customized by user.
msoBarNoResize | 2 | Command bar cannot be resized.
msoBarNoVerticalDock | 32 | Command bar cannot be docked to the left or right.


MsoBarRow Enumeration (Office)

 Copy code hover
[image]

MsoBarRow Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies whether a command bar is in the first row or last row relative to other command bars in the same docking area.

Name | Value | Description
msoBarRowFirst | 0 | First row of docking area.
msoBarRowLast | -1 | Last row of docking area.


MsoBarType Enumeration (Office)

 Copy code hover
[image]

MsoBarType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type of the command bar.

Name | Value | Description
msoBarTypeMenuBar | 1 | Menu bar.
msoBarTypeNormal | 0 | Default command bar.
msoBarTypePopup | 2 | Shortcut menu.


MsoBaselineAlignment Enumeration (Office)

 Copy code hover
[image]

MsoBaselineAlignment Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies baseline text alignment.

Name | Value | Description
msoBaselineAlignAuto | 5 | Automatic alignment.
msoBaselineAlignBaseline | 1 | Baseline alignment.
msoBaselineAlignCenter | 3 | Center alignment.
msoBaselineAlignFarEast50 | 4 | East Asia 50 alignment.
msoBaselineAlignMixed | -2 | Return value only; indicates a combination of the other states.
msoBaselineAlignTop | 2 | Top alignment.


MsoBevelType Enumeration (Office)

 Copy code hover
[image]

MsoBevelType Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the bevel type of a ThreeDFormat object.

Name | Value | Description
msoBevelAngle | 6 | Specifies an Angle bevel.
msoBevelArtDeco | 13 | Specifies an ArtDeco bevel.
msoBevelCircle | 3 | Specifies a Circle bevel.
msoBevelConvex | 8 | Specifies a Convex bevel.
msoBevelCoolSlant | 9 | Specifies a CoolSlant bevel.
msoBevelCross | 5 | Specifies a Cross bevel.
msoBevelDivot | 10 | Specifies a Divot bevel.
msoBevelHardEdge | 12 | Specifies a HardEdge bevel.
msoBevelNone | 1 | Specifies no bevel.
msoBevelRelaxedInset | 2 | Specifies a RelaxedInset bevel.
msoBevelRiblet | 11 | Specifies a Riblet bevel.
msoBevelSlope | 4 | Specifies a Slope bevel.
msoBevelSoftRound | 7 | Specifies a SoftRound bevel.
msoBevelTypeMixed | -2 | Specifies a mixed type bevel.


MsoBlackWhiteMode Enumeration (Office)

 Copy code hover
[image]

MsoBlackWhiteMode Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies how a shape appears when viewed in black-and-white mode.

Name | Value | Description
msoBlackWhiteAutomatic | 1 | Default behavior.
msoBlackWhiteBlack | 8 | Black.
msoBlackWhiteBlackTextAndLine | 6 | White with grayscale fill.
msoBlackWhiteDontShow | 10 | Not shown.
msoBlackWhiteGrayOutline | 5 | Gray with white fill.
msoBlackWhiteGrayScale | 2 | Grayscale.
msoBlackWhiteHighContrast | 7 | Black with white fill.
msoBlackWhiteInverseGrayScale | 4 | Inverse grayscale.
msoBlackWhiteLightGrayScale | 3 | Light grayscale.
msoBlackWhiteMixed | -2 | Not supported.
msoBlackWhiteWhite | 9 | White.


MsoBlogCategorySupport Enumeration (Office)

 Copy code hover
[image]

MsoBlogCategorySupport Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies how many categories are supported by the provider.

Name | Value | Description
msoBlogMultipleCategories | 2 | Multiple categories are supported.
msoBlogNoCategories | 0 | No categories are supported.
msoBlogOneCategory | 1 | One category is supported.


MsoBlogImageType Enumeration (Office)

 Copy code hover
[image]

MsoBlogImageType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies blog image types.

Name | Value | Description
msoBlogImageTypeGIF | 2 | GIF image.
msoBlogImageTypeJPEG | 1 | JPEG image.
msoBlogImageTypePNG | 3 | PNG image.


MsoBroadcastCapabilities Enumeration (Office)

 Copy code hover
[image]

MsoBroadcastCapabilities Enumeration (Office)
Send feedback

Specifies the application capabilities available for a document or presentation broadcasting session.

Version information

Version Added: Office 2013

Members

Name | Value | Description
BroadcastCapFileSizeLimited | 1 | The size of the file being broadcasted is limited.
BroadcastCapSupportsMeetingNotes | 2 | The presenters and attendees can take shared notes.
BroadcastCapSupportsUpdateDoc | 4 | The presenters and attendees can make updates to the file during the broadcast.
BroadcastCapFileSizeLimited | 1 |
BroadcastCapSupportsMeetingNotes | 2 |
BroadcastCapSupportsUpdateDoc | 4 |


MsoBroadcastState Enumeration (Office)

 Copy code hover
[image]

MsoBroadcastState Enumeration (Office)
Send feedback

Specifies the current state of a document or presentation broadcast.

Version information

Version Added: Office 2013

Members

Name | Value | Description
BroadcastPaused | 2 | The broadcast is paused.
BroadcastStarted | 1 | The broadcast has been started.
NoBroadcast | 0 | The file is not being broadcasted.
BroadcastPaused | 2 |
BroadcastStarted | 1 |
NoBroadcast | 0 |


MsoBulletType Enumeration (Office)

 Copy code hover
[image]

MsoBulletType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the bullet type.

Name | Value | Description
msoBulletMixed | -2 | Return value only; indicates a combination of the other states.
msoBulletNone | 0 | No bullets.
msoBulletNumbered | 2 | Numbered bullets.
msoBulletPicture | 3 | Picture bullets.
msoBulletUnnumbered | 1 | Unnumbered bullets.


MsoButtonSetType Enumeration (Office)

 Copy code hover
[image]

MsoButtonSetType Enumeration (Office)
Send feedback

This object or member is deprecated and is not intended to be used in your code.


MsoButtonState Enumeration (Office)

 Copy code hover
[image]

MsoButtonState Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the appearance of a command bar button control.

Name | Value | Description
msoButtonDown | -1 | Button is pressed down.
msoButtonMixed | 2 | Button is pressed down.
msoButtonUp | 0 | Button is not pressed down.


MsoButtonStyle Enumeration (Office)

 Copy code hover
[image]

MsoButtonStyle Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the style of a command bar button.

Name | Value | Description
msoButtonAutomatic | 0 | Default behavior.
msoButtonCaption | 2 | Text only.
msoButtonIcon | 1 | Image only.
msoButtonIconAndCaption | 3 | Image and text, with text to the right of image.
msoButtonIconAndCaptionBelow | 11 | Image with text below.
msoButtonIconAndWrapCaption | 7 | Image with text wrapped and to the right of the image.
msoButtonIconAndWrapCaptionBelow | 15 | Image with text wrapped below image.
msoButtonWrapCaption | 14 | Text only, centered and wrapped.


MsoCalloutAngleType Enumeration (Office)

 Copy code hover
[image]

MsoCalloutAngleType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the size of the angle between the callout line and the side of the callout text box.

Name | Value | Description
msoCalloutAngle30 | 2 | 30° angle.
msoCalloutAngle45 | 3 | 45° angle.
msoCalloutAngle60 | 4 | 60° angle.
msoCalloutAngle90 | 5 | 90° angle.
msoCalloutAngleAutomatic | 1 | Default angle. Angle can be changed as you drag the object.
msoCalloutAngleMixed | -2 | Return value only; indicates a combination of the other states.


MsoCalloutDropType Enumeration (Office)

 Copy code hover
[image]

MsoCalloutDropType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies starting position of the callout line relative to the text bounding box. Used with the PresetDrop method of the CalloutFormat object.

Name | Value | Description
msoCalloutDropBottom | 4 | Bottom.
msoCalloutDropCenter | 3 | Center.
msoCalloutDropCustom | 1 | Custom. If this value is used as the value for the PresetDrop property, the Drop and AutoAttach properties of the CalloutFormat object are used to determine where the callout line attaches to the text box.
msoCalloutDropMixed | -2 | Return value only; indicates a combination of the other states.
msoCalloutDropTop | 2 | Top.


MsoCalloutType Enumeration (Office)

 Copy code hover
[image]

MsoCalloutType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type of callout line.

Name | Value | Description
msoCalloutFour | 4 | Callout line made up of two line segments. Callout line is attached on right side of text bounding box.
msoCalloutMixed | -2 | Return value only; indicates a combination of the other states.
msoCalloutOne | 1 | Single, horizontal callout line.
msoCalloutThree | 3 | Callout line made up of two line segments. Callout line is attached on left side of text bounding box.
msoCalloutTwo | 2 | Single, angled callout line.


MsoCharacterSet Enumeration (Office)

 Copy code hover
[image]

MsoCharacterSet Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the character set to be used when rendering text.

Name | Value | Description
msoCharacterSetArabic | 1 | Arabic character set.
msoCharacterSetCyrillic | 2 | Cyrillic character set.
msoCharacterSetEnglishWesternEuropeanOtherLatinScript | 3 | English, Western European, and other Latin script character set.
msoCharacterSetGreek | 4 | Greek character set.
msoCharacterSetHebrew | 5 | Hebrew character set.
msoCharacterSetJapanese | 6 | Japanese character set.
msoCharacterSetKorean | 7 | Korean character set.
msoCharacterSetMultilingualUnicode | 8 | Multilingual Unicode character set.
msoCharacterSetSimplifiedChinese | 9 | Simplified Chinese character set.
msoCharacterSetThai | 10 | Thai character set.
msoCharacterSetTraditionalChinese | 11 | Traditional Chinese character set.
msoCharacterSetVietnamese | 12 | Vietnamese character set.


MsoChartElementType Enumeration (Office)

 Copy code hover
[image]

MsoChartElementType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies whether and how to display chart elements.

Version Information

Version Added: Office Core 2007

Name | Value | Description
msoElementChartFloorNone | 1200 | Do not display chart floor.
msoElementChartFloorShow | 1201 | Display chart floor.
msoElementChartTitleAboveChart | 2 | Display title above chart.
msoElementChartTitleCenteredOverlay | 1 | Display title as centered overlay.
msoElementChartTitleNone | 0 | Do not display chart title.
msoElementChartWallNone | 1100 | Do not display chart wall.
msoElementChartWallShow | 1101 | Dispaly chart wall.
msoElementDataLabelBestFit | 210 | Use best fit for data label.
msoElementDataLabelBottom | 209 | Display data label at bottom.
msoElementDataLabelCallout | 211 | Display data label as a callout.
msoElementDataLabelCenter | 202 | Display data label in center.
msoElementDataLabelInsideBase | 204 | Display data label inside at the base.
msoElementDataLabelInsideEnd | 203 | Display data label inside at the end.
msoElementDataLabelLeft | 206 | Display data label to the left.
msoElementDataLabelNone | 200 | Do not display data label.
msoElementDataLabelOutSideEnd | 205 | Display data label outside at the end.
msoElementDataLabelRight | 207 | Display data label to the right.
msoElementDataLabelShow | 201 | Display data label.
msoElementDataLabelTop | 208 | Display data label at the top.
msoElementDataTableNone | 500 | Do not display data table.
msoElementDataTableShow | 501 | Display data table.
msoElementDataTableWithLegendKeys | 502 | Display data table with legend keys.
msoElementErrorBarNone | 700 | Do not display error bar.
msoElementErrorBarPercentage | 702 | Display percentage error bar.
msoElementErrorBarStandardDeviation | 703 | Display standard deviation error bar.
msoElementErrorBarStandardError | 701 | Display standard error bar.
msoElementLegendBottom | 104 | Display legend at the bottom.
msoElementLegendLeft | 103 | Display legend at the left.
msoElementLegendLeftOverlay | 106 | Overlay legend at the left.
msoElementLegendNone | 100 | Do not display legend.
msoElementLegendRight | 101 | Display legend at the right.
msoElementLegendRightOverlay | 105 | Overlay legend at the right.
msoElementLegendTop | 102 | Display legend at the top.
msoElementLineDropHiLoLine | 804 | Display drop high/low line.
msoElementLineDropLine | 801 | Display drop line.
msoElementLineHiLoLine | 802 | Display high/low line.
msoElementLineNone | 800 | Do not display line.
msoElementLineSeriesLine | 803 | Display series line.
msoElementPlotAreaNone | 1000 | Do not display plot area.
msoElementPlotAreaShow | 1001 | Display plot area.
msoElementPrimaryCategoryAxisBillions | 374 | Use billions for primary category axis units.
msoElementPrimaryCategoryAxisLogScale | 375 | Use log scale for primary category axis.
msoElementPrimaryCategoryAxisMillions | 373 | Use millions for primary category axis units.
msoElementPrimaryCategoryAxisNone | 348 | Do not display primary category axis.
msoElementPrimaryCategoryAxisReverse | 351 | Reverse primary category axis.
msoElementPrimaryCategoryAxisShow | 349 | Show primary category axis.
msoElementPrimaryCategoryAxisThousands | 372 | Use thousands for primary category axis units.
msoElementPrimaryCategoryAxisTitleAdjacentToAxis | 301 | Display primary category axis title adjacent to the axis.
msoElementPrimaryCategoryAxisTitleBelowAxis | 302 | Display primary category axis title below the axis.
msoElementPrimaryCategoryAxisTitleHorizontal | 305 | Display primary category axis title horizontally.
msoElementPrimaryCategoryAxisTitleNone | 300 | Do not display primary category axis title.
msoElementPrimaryCategoryAxisTitleRotated | 303 | Rotate primary category axis title.
msoElementPrimaryCategoryAxisTitleVertical | 304 | Display primary category axis title vertically.
msoElementPrimaryCategoryAxisWithoutLabels | 350 | Display primary category axis without labels.
msoElementPrimaryCategoryGridLinesMajor | 334 | Display major gridlines along primary category axis.
msoElementPrimaryCategoryGridLinesMinor | 333 | Display minor gridlines along primary category axis.
msoElementPrimaryCategoryGridLinesMinorMajor | 335 | Display both major and minor gridlines along primary category axis.
msoElementPrimaryCategoryGridLinesNone | 332 | Do not display grid lines along primary category axis.
msoElementPrimaryValueAxisBillions | 356 | Use billions for primary value axis units.
msoElementPrimaryValueAxisLogScale | 357 | Use log scale for primary value axis.
msoElementPrimaryValueAxisMillions | 355 | Use millions for primary value axis units.
msoElementPrimaryValueAxisNone | 352 | Do not display primary value axis.
msoElementPrimaryValueAxisShow | 353 | Show primary value axis
msoElementPrimaryValueAxisThousands | 354 | Use thousands for primary value axis units.
msoElementPrimaryValueAxisTitleAdjacentToAxis | 306 | Place primary value axis title adjacent to the axis.
msoElementPrimaryValueAxisTitleBelowAxis | 308 | Place primary value axis title below the axis.
msoElementPrimaryValueAxisTitleHorizontal | 311 | Display primary value axis title horizontally.
msoElementPrimaryValueAxisTitleNone | 306 | Do not display primary value axis title.
msoElementPrimaryValueAxisTitleRotated | 309 | Rotate primary value axis title.
msoElementPrimaryValueAxisTitleVertical | 310 | Display primary value axis title vertically.
msoElementPrimaryValueGridLinesMajor | 330 | Display major gridlines along primary value axis.
msoElementPrimaryValueGridLinesMinor | 329 | Display minor gridlines along primary value axis.
msoElementPrimaryValueGridLinesMinorMajor | 331 | Display both major and minor gridlines along primary value axis.
msoElementPrimaryValueGridLinesNone | 328 | Do not display grid lines along primary value axis.
msoElementSecondaryCategoryAxisBillions | 378 | Use billions for secondary category axis units.
msoElementSecondaryCategoryAxisLogScale | 379 | Use log scale for secondary category axis.
msoElementSecondaryCategoryAxisMillions | 377 | Use millions for secondary category axis units.
msoElementSecondaryCategoryAxisNone | 358 | Do not display secondary category axis.
msoElementSecondaryCategoryAxisReverse | 361 | Reverse secondary category axis.
msoElementSecondaryCategoryAxisShow | 359 | Display secondary category axis.
msoElementSecondaryCategoryAxisThousands | 376 | Use thousands for secondary category axis units.
msoElementSecondaryCategoryAxisTitleAdjacentToAxis | 313 | Dispaly secondary category axis title adjacent to axis.
msoElementSecondaryCategoryAxisTitleBelowAxis | 314 | Dispaly secondary category axis title below axis.
msoElementSecondaryCategoryAxisTitleHorizontal | 317 | Display secondary category axis title horizontally.
msoElementSecondaryCategoryAxisTitleNone | 312 | Do not display secondary category axis title.
msoElementSecondaryCategoryAxisTitleRotated | 315 | Rotate secondary category axis title.
msoElementSecondaryCategoryAxisTitleVertical | 316 | Display secondary category axis title vertically.
msoElementSecondaryCategoryAxisWithoutLabels | 360 | Display secondary category axis without labels.
msoElementSecondaryCategoryGridLinesMajor | 342 | Display major gridlines along secondary category axis.
msoElementSecondaryCategoryGridLinesMinor | 341 | Display minor gridlines along secondary category axis.
msoElementSecondaryCategoryGridLinesMinorMajor | 343 | Display both major and minor gridlines along secondary category axis.
msoElementSecondaryCategoryGridLinesNone | 340 | Do not display grid lines along secondary category axis.
msoElementSecondaryValueAxisBillions | 366 | Use billions for secondary value axis units.
msoElementSecondaryValueAxisLogScale | 367 | Use log scale for secondary value axis.
msoElementSecondaryValueAxisMillions | 365 | Use millions for secondary value axis units.
msoElementSecondaryValueAxisNone | 362 | Do not display secondary value axis.
msoElementSecondaryValueAxisShow | 363 | Display secondary value axis.
msoElementSecondaryValueAxisThousands | 364 | Use thousands for secondary value axis units.
msoElementSecondaryValueAxisTitleAdjacentToAxis | 319 | Display secondary value axis title adjacent to axis.
msoElementSecondaryValueAxisTitleBelowAxis | 320 | Display secondary value axis title below axis.
msoElementSecondaryValueAxisTitleHorizontal | 323 | Display secondary value axis title horizontally.
msoElementSecondaryValueAxisTitleNone | 318 | Do not display secondary value axis title.
msoElementSecondaryValueAxisTitleRotated | 321 | Rotate secondary value axis title.
msoElementSecondaryValueAxisTitleVertical | 322 | Display secondary value axis title vertically.
msoElementSecondaryValueGridLinesMajor | 338 | Display major gridlines along secondary value axis.
msoElementSecondaryValueGridLinesMinor | 337 | Display minor gridlines along secondary value axis.
msoElementSecondaryValueGridLinesMinorMajor | 339 | Display both major and minor gridlines along secondary value axis.
msoElementSecondaryValueGridLinesNone | 336 | Do not display gridlines along secondary value axis.
msoElementSeriesAxisGridLinesMajor | 346 | Display major gridlines along series axis.
msoElementSeriesAxisGridLinesMinor | 345 | Display minor gridlines along series axis.
msoElementSeriesAxisGridLinesMinorMajor | 347 | Display both major and minor gridlines along series axis.
msoElementSeriesAxisGridLinesNone | 344 | Do not display gridlines along series axis.
msoElementSeriesAxisNone | 368 | Do not display series axis.
msoElementSeriesAxisReverse | 371 | Reverse series axis.
msoElementSeriesAxisShow | 369 | Display series axis.
msoElementSeriesAxisTitleHorizontal | 327 | Display series axis title horizontally.
msoElementSeriesAxisTitleNone | 324 | Do not display series axis title.
msoElementSeriesAxisTitleRotated | 325 | Rotate series axis title.
msoElementSeriesAxisTitleVertical | 326 | Display series axis title vertically.
msoElementSeriesAxisWithoutLabeling | 370 | Display series axis title without labeling.
msoElementTrendlineAddExponential | 602 | Add an exponential trendline.
msoElementTrendlineAddLinear | 601 | Add a linear trendline.
msoElementTrendlineAddLinearForecast | 603 | Add a linear forecast.
msoElementTrendlineAddTwoPeriodMovingAverage | 604 | Add a two-period moving average.
msoElementTrendlineNone | 600 | Do not display trendline.
msoElementUpDownBarsNone | 900 | Do not display up/down bars.
msoElementUpDownBarsShow | 901 | Display up/down bars.


MsoChartFieldType Enumeration (Office)

 Copy code hover
[image]

MsoChartFieldType Enumeration (Office)
Send feedback

Specifies the type of data field to be inserted into a data label in a chart.

Version information

Version Added: Office 2013

Members

Name | Value | Description
msoChartFieldBubbleSize | 1 | Specifies the Bubble size of the data point.
msoChartFieldCategoryName | 2 | Specifies the category name size of the data point.
msoChartFieldFormula | 6 | Specifies the formula used in the data point.
msoChartFieldPercentage | 3 | Specifies a percentage of the values.
msoChartFieldSeriesName | 4 | Specifies the data series name.
msoChartFieldValue | 5 | Specifies the value of the data field.
msoChartFieldRange | 7 | Specifies the value of a range of data.
msoChartFieldBubbleSize | 1 |
msoChartFieldCategoryName | 2 |
msoChartFieldFormula | 6 |
msoChartFieldPercentage | 3 |
msoChartFieldSeriesName | 4 |
msoChartFieldValue | 5 |


MsoClipboardFormat Enumeration (Office)

 Copy code hover
[image]

MsoClipboardFormat Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies Clipboard formats.

Version Information

Version Added: Office Core 2007

Name | Value | Description
msoClipboardFormatHTML | 2 | HTML format.
msoClipboardFormatMixed | -2 | Return value only; indicates a combination of the other states.
msoClipboardFormatNative | 1 | Native format.
msoClipboardFormatPlainText | 4 | Plain text format.
msoClipboardFormatRTF | 3 | RTF format.


MsoColorType Enumeration (Office)

 Copy code hover
[image]

MsoColorType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the color type.

Name | Value | Description
msoColorTypeCMS | 4 | Color Management System color type.
msoColorTypeCMYK | 3 | Color is determined by values of cyan, magenta, yellow, and black.
msoColorTypeInk | 5 | Not supported.
msoColorTypeMixed | -2 | Not supported.
msoColorTypeRGB | 1 | Color is determined by values of red, green, and blue.
msoColorTypeScheme | 2 | Color is defined by an application-specific scheme.


MsoComboStyle Enumeration (Office)

 Copy code hover
[image]

MsoComboStyle Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies whether the command bar combo box includes a label or not.

Name | Value | Description
msoComboLabel | 1 | Combo box includes a label, specified by the Caption property of the combo box.
msoComboNormal | 0 | Combo box does not include a label.


MsoCommandBarButtonHyperlinkType Enumeration (Office)

 Copy code hover
[image]

MsoCommandBarButtonHyperlinkType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies whether the command bar button is a hyperlink. If the command bar button is a hyperlink, further specifies whether the hyperlink should launch another application such as the browser or insert a picture at the active selection point.

Name | Value | Description
msoCommandBarButtonHyperlinkInsertPicture | 2 | Clicking the command bar button inserts a picture at the active selection point.
msoCommandBarButtonHyperlinkNone | 0 | The command bar button is not a hyperlink.
msoCommandBarButtonHyperlinkOpen | 1 | Clicking the command bar button opens the link specified in the command bar button's TooltipText property.


MsoConnectorType Enumeration (Office)

 Copy code hover
[image]

MsoConnectorType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies a type of connector.

Version Information

Version Added: Office System 2003

Name | Value | Description
msoConnectorCurve | 3 | Curved connector.
msoConnectorElbow | 2 | Elbow connector.
msoConnectorStraight | 1 | Straight line connector.
msoConnectorTypeMixed | -2 | Return value only; indicates a combination of the other states.


MsoContactCardAddressType Enumeration (Office)

 Copy code hover
[image]

MsoContactCardAddressType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the address type for a contact card.

Version Information

Version Added: Office 2010

Name | Value | Description
msoContactCardAddressTypeUnknown | 0 | An unknown identifier for an address.
msoContactCardAddressTypeOutlook | 1 | A unique identifier for an Outlook address.
msoContactCardAddressTypeSMTP | 2 | A unique identifier for an SMTP address.
msoContactCardAddressTypeIM | 1 | A unique identifier for an IM address.


MsoContactCardStyle Enumeration (Office)

 Copy code hover
[image]

MsoContactCardStyle Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies how the contact card is displayed.

Version Information

Version Added: Office 2010

Name | Value | Description
msoContactCardFull | 1 | The contact card is displayed as a full card.
msoContactCardHover | 0 | The contact card is displayed as a hover card.


MsoContactCardType Enumeration (Office)

 Copy code hover
[image]

MsoContactCardType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the contact card type.

Version Information

Version Added: Office 2010

Name | Value | Description
msoContactCardTypeEnterpriseContact | 0 | A contact card for an enterprise contact address.
msoContactCardTypePersonalContact | 1 | A contact card for a personal contact address.
msoContactCardTypeUnknownContact | 2 | A contact card for an unknown contact address.
msoContactCardTypeEnterpriseGroup | 3 | A contact card for an enterprise distribution list contact address.
msoContactCardTypePersonalDistributionList | 4 | A contact card for a personal distribution list contact address.


MsoControlOLEUsage Enumeration (Office)

 Copy code hover
[image]

MsoControlOLEUsage Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the OLE client and OLE server roles in which a command bar control is used when two Microsoft Office applications are merged.

Name | Value | Description
msoControlOLEUsageBoth | 3 | Control runs on both client and server.
msoControlOLEUsageClient | 2 | Client-only control.
msoControlOLEUsageNeither | 0 | Control runs on neither client nor server.
msoControlOLEUsageServer | 1 | Server-only control.


MsoControlType Enumeration (Office)

 Copy code hover
[image]

MsoControlType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type of the command bar control. Used with the Add method of the CommandBarControls object. Only a limited set of the control types can be created via the CommandBars object model: msoControlButton, msoControlEdit, msoControlDropdown, msoControlComboBox, msoControlPopup, and msoControlActiveX. Other control types may exist on built-in or add-in command bars, but cannot be created via the object model.

Name | Value | Description
msoControlActiveX | 22 | ActiveX control.
msoControlAutoCompleteCombo | 26 | Combo box in which the first matching choice is automatically filled in as the user types. Cannot be created through the object model.
msoControlButton | 1 | Command button.
msoControlButtonDropdown | 5 | Drop-down button. Cannot be created through the object model.
msoControlButtonPopup | 12 | Pop-up button. Cannot be created through the object model.
msoControlComboBox | 4 | Combo box.
msoControlCustom | 0 | Custom control. Cannot be created through the object model.
msoControlDropdown | 3 | Drop-down list.
msoControlEdit | 2 | Text box.
msoControlExpandingGrid | 16 | Expanding grid. Cannot be created through the object model.
msoControlGauge | 19 | Gauge control. Cannot be created through the object model.
msoControlGenericDropdown | 8 | Generic drop-down list. Cannot be created through the object model.
msoControlGraphicCombo | 20 | Graphic combo box. Cannot be created through the object model.
msoControlGraphicDropdown | 9 | Graphic drop-down list. Cannot be created through the object model.
msoControlGraphicPopup | 11 | Graphic pop-up menu. Cannot be created through the object model.
msoControlGrid | 18 | Grid. Cannot be created through the object model.
msoControlLabel | 15 | Label. Cannot be created through the object model.
msoControlLabelEx | 24 | Extended label. Cannot be created through the object model.
msoControlOCXDropdown | 7 | OCX drop-down list. Cannot be created through the object model.
msoControlPane | 21 | Pane. Cannot be created through the object model.
msoControlPopup | 10 | Pop-up.
msoControlSpinner | 23 | Spinner. Cannot be created through the object model.
msoControlSplitButtonMRUPopup | 14 | Most Recently Used (MRU) pop-up. Cannot be created through the object model.
msoControlSplitButtonPopup | 13 | Split button pop-up. Cannot be created through the object model.
msoControlSplitDropdown | 6 | Split drop-down list. Cannot be created through the object model.
msoControlSplitExpandingGrid | 17 | Split expanding grid. Cannot be created through the object model.
msoControlWorkPane | 25 | Work pane. Cannot be created through the object model.


MsoCTPDockPosition Enumeration (Office)

 Copy code hover
[image]

MsoCTPDockPosition Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the docking behavior of the custom task pane.

Name | Value | Description
msoCTPDockPositionBottom | 3 | Dock the task pane at the bottom of the document window.
msoCTPDockPositionFloating | 4 | Don't dock the task pane.
msoCTPDockPositionLeft | 0 | Dock the task pane on the left side of the document window.
msoCTPDockPositionRight | 2 | Dock the task pane on the right side of the document window.
msoCTPDockPositionTop | 1 | Dock the task pane at the top of the document window.


MsoCTPDockPositionRestrict Enumeration (Office)

 Copy code hover
[image]

MsoCTPDockPositionRestrict Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies retrictions on the docking behavior of the custom task pane.

Name | Value | Description
msoCTPDockPositionRestrictNoChange | 1 | There is no change from the current restriction setting for the task pane.
msoCTPDockPositionRestrictNoHorizontal | 2 | Task pane can't be docked to either the right or the left side of the document window.
msoCTPDockPositionRestrictNone | 0 | No restrictions on docking the task pane.
msoCTPDockPositionRestrictNoVertical | 3 | Task pane can't be docked to either the top or the bottom of the document window.


MsoCustomXMLNodeType Enumeration (Office)

 Copy code hover
[image]

MsoCustomXMLNodeType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the node type.

Name | Value | Description
msoCustomXMLNodeAttribute | 2 | The node is an attribute.
msoCustomXMLNodeCData | 4 | The node is a CData type.
msoCustomXMLNodeComment | 8 | The node is a comment.
msoCustomXMLNodeDocument | 9 | The node is a Document node.
msoCustomXMLNodeElement | 1 | The node is an element.
msoCustomXMLNodeProcessingInstruction | 7 | The node is a processing instruction.
msoCustomXMLNodeText | 3 | The node is a text node.


MsoCustomXMLValidationErrorType Enumeration (Office)

 Copy code hover
[image]

MsoCustomXMLValidationErrorType Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates how validation errors will be cleared or generated.

Name | Value | Description
msoCustomXMLValidationErrorAutomaticallyCleared | 1 | Specifies that the error will clear itself whenever any change is made to the node it is bound to.
msoCustomXMLValidationErrorManual | 2 | Specifies that the error will not be cleared until the Delete method is called.
msoCustomXMLValidationErrorSchemaGenerated | 0 | Specifies that where there is a non-empty schema collection available for the custom XML part and validation is in effect, any changes to the part will cause validation errors.


MsoDateTimeFormat Enumeration (Office)

 Copy code hover
[image]

MsoDateTimeFormat Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the format of a date/time data type.

Name | Value | Description
msoDateTimeddddMMMMddyyyy | 2 | Specifies a ddddMMMMddyyyy format.
msoDateTimedMMMMyyyy | 3 | Specifies MMMMyyyy format.
msoDateTimedMMMyy | 5 | Specifies MMMyy format.
msoDateTimeFigureOut | 14 | Specifies that the Office application will determine the format.
msoDateTimeFormatMixed | -2 | Specifies a mixed format.
msoDateTimeHmm | 10 | Specifies Hmm format.
msoDateTimehmmAMPM | 12 | Specifies a hmmAMPM format.
msoDateTimeHmmss | 11 | Specifies a Hmmss format.
msoDateTimehmmssAMPM | 13 | Specifies a hmmssAMPM format.
msoDateTimeMdyy | 1 | Specifies a Mdyy format.
msoDateTimeMMddyyHmm | 8 | Specifies a MMddyyHmm format.
msoDateTimeMMddyyhmmAMPM | 9 | Specifies a MMddyyhmmAMPM format.
msoDateTimeMMMMdyyyy | 4 | Specifies a MMMMdyyyy format.
msoDateTimeMMMMyy | 6 | Specifies a MMMMyy format.
msoDateTimeMMyy | 7 | Specifies a MMyy format.


MsoDistributeCmd Enumeration (Office)

 Copy code hover
[image]

MsoDistributeCmd Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies how to evenly distribute a collection of shapes. Used with the Distribute method of the ShapeRange collection.

Name | Value | Description
msoDistributeHorizontally | 0 | Distribute horizontally.
msoDistributeVertically | 1 | Distribute vertically.


MsoDocInspectorStatus Enumeration (Office)

 Copy code hover
[image]

MsoDocInspectorStatus Enumeration (Office)
Send feedback

Published: July 09, 2012

Represents the results of running a Document Inspector module.

Name | Value | Description
msoDocInspectorStatusDocOk | 0 | Indicates that the Document Inspector module returned no issues or errors.
msoDocInspectorStatusError | 2 | Indicates that the Document Inspector module returned an error.
msoDocInspectorStatusIssueFound | 1 | Indicates that the Document Inspector module found one or more occurrences of the search criteria.


MsoDocProperties Enumeration (Office)

 Copy code hover
[image]

MsoDocProperties Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the data type for a document property.

Name | Value | Description
msoPropertyTypeBoolean | 2 | Boolean value.
msoPropertyTypeDate | 3 | Date value.
msoPropertyTypeFloat | 5 | Floating point value.
msoPropertyTypeNumber | 1 | Integer value.
msoPropertyTypeString | 4 | String value.


MsoEditingType Enumeration (Office)

 Copy code hover
[image]

MsoEditingType Enumeration (Office)
Send feedback

Specifies the editing type of a node.

Name | Value | Description
msoEditingAuto | 0 | Editing type is appropriate to the segments being connected.
msoEditingCorner | 1 | Corner node.
msoEditingSmooth | 2 | Smooth node.
msoEditingSymmetric | 3 | Symmetric node.


MsoEncoding Enumeration (Office)

 Copy code hover
[image]

MsoEncoding Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the document encoding (code page or character set) for the Web browser to use when a user views a saved document.

Name | Value | Description
msoEncodingArabic | 1256 | Arabic.
msoEncodingArabicASMO | 708 | Arabic ASMO.
msoEncodingArabicAutoDetect | 51256 | Web browser auto-detects type of Arabic encoding to use.
msoEncodingArabicTransparentASMO | 720 | Transparent Arabic.
msoEncodingAutoDetect | 50001 | Web browser auto-detects type of encoding to use.
msoEncodingBaltic | 1257 | Baltic.
msoEncodingCentralEuropean | 1250 | Central European.
msoEncodingCyrillic | 1251 | Cyrillic.
msoEncodingCyrillicAutoDetect | 51251 | Web browser auto-detects type of Cyrillic encoding to use.
msoEncodingEBCDICArabic | 20420 | Extended Binary Coded Decimal Interchange Code (EBCDIC) Arabic.
msoEncodingEBCDICDenmarkNorway | 20277 | EBCDIC as used in Denmark and Norway.
msoEncodingEBCDICFinlandSweden | 20278 | EBCDIC as used in Finland and Sweden.
msoEncodingEBCDICFrance | 20297 | EBCDIC as used in France.
msoEncodingEBCDICGermany | 20273 | EBCDIC as used in Germany.
msoEncodingEBCDICGreek | 20423 | EBCDIC as used in the Greek language.
msoEncodingEBCDICGreekModern | 875 | EBCDIC as used in the Modern Greek language.
msoEncodingEBCDICHebrew | 20424 | EBCDIC as used in the Hebrew language.
msoEncodingEBCDICIcelandic | 20871 | EBCDIC as used in Iceland.
msoEncodingEBCDICInternational | 500 | International EBCDIC.
msoEncodingEBCDICItaly | 20280 | EBCDIC as used in Italy.
msoEncodingEBCDICJapaneseKatakanaExtended | 20290 | EBCDIC as used with Japanese Katakana (extended).
msoEncodingEBCDICJapaneseKatakanaExtendedAndJapanese | 50930 | EBCDIC as used with Japanese Katakana (extended) and Japanese.
msoEncodingEBCDICJapaneseLatinExtendedAndJapanese | 50939 | EBCDIC as used with Japanese Latin (extended) and Japanese.
msoEncodingEBCDICKoreanExtended | 20833 | EBCDIC as used with Korean (extended).
msoEncodingEBCDICKoreanExtendedAndKorean | 50933 | EBCDIC as used with Korean (extended) and Korean.
msoEncodingEBCDICLatinAmericaSpain | 20284 | EBCDIC as used in Latin America and Spain.
msoEncodingEBCDICMultilingualROECELatin2 | 870 | EBCDIC Multilingual ROECE (Latin 2).
msoEncodingEBCDICRussian | 20880 | EBCDIC as used with Russian.
msoEncodingEBCDICSerbianBulgarian | 21025 | EBCDIC as used with Serbian and Bulgarian.
msoEncodingEBCDICSimplifiedChineseExtendedAndSimplifiedChinese | 50935 | EBCDIC as used with Simplified Chinese (extended) and Simplified Chinese.
msoEncodingEBCDICThai | 20838 | EBCDIC as used with Thai.
msoEncodingEBCDICTurkish | 20905 | EBCDIC as used with Turkish.
msoEncodingEBCDICTurkishLatin5 | 1026 | EBCDIC as used with Turkish (Latin 5).
msoEncodingEBCDICUnitedKingdom | 20285 | EBCDIC as used in the United Kingdom.
msoEncodingEBCDICUSCanada | 37 | EBCDIC as used in the United States and Canada.
msoEncodingEBCDICUSCanadaAndJapanese | 50931 | EBCDIC as used in the United States and Canada, and with Japanese.
msoEncodingEBCDICUSCanadaAndTraditionalChinese | 50937 | EBCDIC as used in the United States and Canada, and with Traditional Chinese.
msoEncodingEUCChineseSimplifiedChinese | 51936 | Extended Unix Code (EUC) as used with Chinese and Simplified Chinese.
msoEncodingEUCJapanese | 51932 | EUC as used with Japanese.
msoEncodingEUCKorean | 51949 | EUC as used with Korean.
msoEncodingEUCTaiwaneseTraditionalChinese | 51950 | EUC as used with Taiwanese and Traditional Chinese.
msoEncodingEuropa3 | 29001 | Europa.
msoEncodingExtAlphaLowercase | 21027 | Extended Alpha lowercase.
msoEncodingGreek | 1253 | Greek.
msoEncodingGreekAutoDetect | 51253 | Web browser auto-detects type of Greek encoding to use.
msoEncodingHebrew | 1255 | Hebrew.
msoEncodingHZGBSimplifiedChinese | 52936 | Simplified Chinese (HZGB).
msoEncodingIA5German | 20106 | German (International Alphabet No. 5, or IA5).
msoEncodingIA5IRV | 20105 | IA5, International Reference Version (IRV).
msoEncodingIA5Norwegian | 20108 | IA5 as used with Norwegian.
msoEncodingIA5Swedish | 20107 | IA5 as used with Swedish.
msoEncodingISCIIAssamese | 57006 | Indian Script Code for Information Interchange (ISCII) as used with Assamese.
msoEncodingISCIIBengali | 57003 | ISCII as used with Bengali.
msoEncodingISCIIDevanagari | 57002 | ISCII as used with Devanagari.
msoEncodingISCIIGujarati | 57010 | ISCII as used with Gujarati.
msoEncodingISCIIKannada | 57008 | ISCII as used with Kannada.
msoEncodingISCIIMalayalam | 57009 | ISCII as used with Malayalam.
msoEncodingISCIIOriya | 57007 | ISCII as used with Oriya.
msoEncodingISCIIPunjabi | 57011 | ISCII as used with Punjabi.
msoEncodingISCIITamil | 57004 | ISCII as used with Tamil.
msoEncodingISCIITelugu | 57005 | ISCII as used with Telugu.
msoEncodingISO2022CNSimplifiedChinese | 50229 | ISO 2022-CN encoding as used with Simplified Chinese.
msoEncodingISO2022CNTraditionalChinese | 50227 | ISO 2022-CN encoding as used with Traditional Chinese.
msoEncodingISO2022JPJISX02011989 | 50222 | ISO 2022-JP
msoEncodingISO2022JPJISX02021984 | 50221 | ISO 2022-JP
msoEncodingISO2022JPNoHalfwidthKatakana | 50220 | ISO 2022-JP with no half-width Katakana.
msoEncodingISO2022KR | 50225 | ISO 2022-KR.
msoEncodingISO6937NonSpacingAccent | 20269 | ISO 6937 Non-Spacing Accent.
msoEncodingISO885915Latin9 | 28605 | ISO 8859-15 with Latin 9.
msoEncodingISO88591Latin1 | 28591 | ISO 8859-1 Latin 1.
msoEncodingISO88592CentralEurope | 28592 | ISO 8859-2 Central Europe.
msoEncodingISO88593Latin3 | 28593 | ISO 8859-3 Latin 3.
msoEncodingISO88594Baltic | 28594 | ISO 8859-4 Baltic.
msoEncodingISO88595Cyrillic | 28595 | ISO 8859-5 Cyrillic.
msoEncodingISO88596Arabic | 28596 | ISA 8859-6 Arabic.
msoEncodingISO88597Greek | 28597 | ISO 8859-7 Greek.
msoEncodingISO88598Hebrew | 28598 | ISO 8859-8 Hebrew.
msoEncodingISO88598HebrewLogical | 38598 | ISO 8859-8 Hebrew (Logical).
msoEncodingISO88599Turkish | 28599 | ISO 8859-9 Turkish.
msoEncodingJapaneseAutoDetect | 50932 | Web browser auto-detects type of Japanese encoding to use.
msoEncodingJapaneseShiftJIS | 932 | Japanese (Shift-JIS).
msoEncodingKOI8R | 20866 | KOI8-R.
msoEncodingKOI8U | 21866 | K0I8-U.
msoEncodingKorean | 949 | Korean.
msoEncodingKoreanAutoDetect | 50949 | Web browser auto-detects type of Korean encoding to use.
msoEncodingKoreanJohab | 1361 | Korean (Johab).
msoEncodingMacArabic | 10004 | Macintosh Arabic.
msoEncodingMacCroatia | 10082 | Macintosh Croatian.
msoEncodingMacCyrillic | 10007 | Macintosh Cyrillic.
msoEncodingMacGreek1 | 10006 | Macintosh Greek.
msoEncodingMacHebrew | 10005 | Macintosh Hebrew.
msoEncodingMacIcelandic | 10079 | Macintosh Icelandic.
msoEncodingMacJapanese | 10001 | Macintosh Japanese.
msoEncodingMacKorean | 10003 | Macintosh Korean.
msoEncodingMacLatin2 | 10029 | Macintosh Latin 2.
msoEncodingMacRoman | 10000 | Macintosh Roman.
msoEncodingMacRomania | 10010 | Macintosh Romanian.
msoEncodingMacSimplifiedChineseGB2312 | 10008 | Macintosh Simplified Chinese (GB 2312).
msoEncodingMacTraditionalChineseBig5 | 10002 | Macintosh Traditional Chinese (Big 5).
msoEncodingMacTurkish | 10081 | Macintosh Turkish.
msoEncodingMacUkraine | 10017 | Macintosh Ukrainian.
msoEncodingOEMArabic | 864 | OEM as used with Arabic.
msoEncodingOEMBaltic | 775 | OEM as used with Baltic.
msoEncodingOEMCanadianFrench | 863 | OEM as used with Canadian French.
msoEncodingOEMCyrillic | 855 | OEM as used with Cyrillic.
msoEncodingOEMCyrillicII | 866 | OEM as used with Cyrillic II.
msoEncodingOEMGreek437G | 737 | OEM as used with Greek 437G.
msoEncodingOEMHebrew | 862 | OEM as used with Hebrew.
msoEncodingOEMIcelandic | 861 | OEM as used with Icelandic.
msoEncodingOEMModernGreek | 869 | OEM as used with Modern Greek.
msoEncodingOEMMultilingualLatinI | 850 | OEM as used with multi-lingual Latin I.
msoEncodingOEMMultilingualLatinII | 852 | OEM as used with multi-lingual Latin II.
msoEncodingOEMNordic | 865 | OEM as used with Nordic languages.
msoEncodingOEMPortuguese | 860 | OEM as used with Portuguese.
msoEncodingOEMTurkish | 857 | OEM as used with Turkish.
msoEncodingOEMUnitedStates | 437 | OEM as used in the United States.
msoEncodingSimplifiedChineseAutoDetect | 50936 | Web browser auto-detects type of Simplified Chinese encoding to use.
msoEncodingSimplifiedChineseGB18030 | 54936 | Simplified Chinese GB 18030.
msoEncodingSimplifiedChineseGBK | 936 | Simplified Chinese GBK.
msoEncodingT61 | 20261 | T61.
msoEncodingTaiwanCNS | 20000 | Taiwan CNS.
msoEncodingTaiwanEten | 20002 | Taiwan Eten.
msoEncodingTaiwanIBM5550 | 20003 | Taiwan IBM 5550.
msoEncodingTaiwanTCA | 20001 | Taiwan TCA.
msoEncodingTaiwanTeleText | 20004 | Taiwan Teletext.
msoEncodingTaiwanWang | 20005 | Taiwan Wang.
msoEncodingThai | 874 | Thai.
msoEncodingTraditionalChineseAutoDetect | 50950 | Web browser auto-detects type of Traditional Chinese encoding to use.
msoEncodingTraditionalChineseBig5 | 950 | Traditional Chinese Big 5.
msoEncodingTurkish | 1254 | Turkish.
msoEncodingUnicodeBigEndian | 1201 | Unicode big endian.
msoEncodingUnicodeLittleEndian | 1200 | Unicode little endian.
msoEncodingUSASCII | 20127 | United States ASCII.
msoEncodingUTF7 | 65000 | UTF-7 encoding.
msoEncodingUTF8 | 65001 | UTF-8 encoding.
msoEncodingVietnamese | 1258 | Vietnamese.
msoEncodingWestern | 1252 | Western.


MsoExtraInfoMethod Enumeration (Office)

 Copy code hover
[image]

MsoExtraInfoMethod Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies how to use the value specified in the ExtraInfo property of the FollowHyperlink method.

Name | Value | Description
msoMethodGet | 0 | The value specified in the ExtraInfo property is a string that is appended to the address.
msoMethodPost | 1 | The value specified in the ExtraInfo property is posted as a string or byte array.


MsoExtrusionColorType Enumeration (Office)

 Copy code hover
[image]

MsoExtrusionColorType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies whether the extrusion color is based on the extruded shape's fill (the front face of the extrusion) and automatically changes when the shape's fill changes, or whether the extrusion color is independent of the shape's fill. Used with the ExtrusionColorType property of the ThreeDFormat object.

Name | Value | Description
msoExtrusionColorAutomatic | 1 | Extrusion color is based on shape fill.
msoExtrusionColorCustom | 2 | Extrusion color is independent of shape fill.
msoExtrusionColorTypeMixed | -2 | Return value only; indicates a combination of the other states.


MsoFarEastLineBreakLanguageID Enumeration (Office)

 Copy code hover
[image]

MsoFarEastLineBreakLanguageID Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the language to use to determine which line break level is used when the line break control option is turned on.

Name | Value | Description
MsoFarEastLineBreakLanguageJapanese | 1041 | Japanese
MsoFarEastLineBreakLanguageKorean | 1042 | Korean
MsoFarEastLineBreakLanguageSimplifiedChinese | 2052 | SimplifiedChinese
MsoFarEastLineBreakLanguageTraditionalChinese | 1028 | TraditionalChinese


MsoFeatureInstall Enumeration (Office)

 Copy code hover
[image]

MsoFeatureInstall Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies how the application handles calls to methods and properties that require features not yet installed.

Name | Value | Description
msoFeatureInstallNone | 0 | Generates a generic automation error at run time when uninstalled features are called.
msoFeatureInstallOnDemand | 1 | Prompts the user to install new features.
msoFeatureInstallOnDemandWithUI | 2 | Displays a progress meter during installation; does not prompt the user to install new features.


MsoFileDialogType Enumeration (Office)

 Copy code hover
[image]

MsoFileDialogType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type of a FileDialog object.

Name | Value | Description
msoFileDialogFilePicker | 3 | File picker dialog box.
msoFileDialogFolderPicker | 4 | Folder picker dialog box.
msoFileDialogOpen | 1 | Open dialog box.
msoFileDialogSaveAs | 2 | Save As dialog box.


MsoFileDialogView Enumeration (Office)

 Copy code hover
[image]

MsoFileDialogView Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the view presented to the user in a file dialog box.

Name | Value | Description
msoFileDialogViewDetails | 2 | Files displayed in a list with detail information.
msoFileDialogViewLargeIcons | 6 | Files displayed as large icons.
msoFileDialogViewList | 1 | Files displayed in a list without details.
msoFileDialogViewPreview | 4 | Files displayed in a list with a preview pane showing the selected file.
msoFileDialogViewProperties | 3 | Files displayed in a list with a pane showing the selected file's properties.
msoFileDialogViewSmallIcons | 7 | Files displayed as small icons.
msoFileDialogViewThumbnail | 5 | Files displayed as thumbnails.
msoFileDialogViewTiles | 9 | Files displayed as tiled icons.
msoFileDialogViewWebView | 8 | Files displayed in Web view.


MsoFileNewAction Enumeration (Office)

 Copy code hover
[image]

MsoFileNewAction Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies action to take when a user clicks an item in the task pane. Used with the Add method of the NewFile object.

Name | Value | Description
msoCreateNewFile | 1 | Create a new file.
msoEditFile | 0 | Edit file.
msoOpenFile | 2 | Open file.


MsoFileNewSection Enumeration (Office)

 Copy code hover
[image]

MsoFileNewSection Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the task pane section to which to add a file or where the file reference exists. Used with the Add method and the Remove method of the NewFile object.

Name | Value | Description
msoBottomSection | 4 | Bottom section.
msoNew | 1 | New section.
msoNewfromExistingFile | 2 | New from Existing File section.
msoNewfromTemplate | 3 | New from Template section.
msoOpenDocument | 0 | Open Document section.


MsoFileValidationMode Enumeration (Office)

 Copy code hover
[image]

MsoFileValidationMode Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the file validation mode.

Version Information

Version Added: Office 2010

Name | Value | Description
msoFileValidationDefault | 0 | Validate the file (default).
msoFileValidationSkip | 1 | Do not validate the file.


MsoFillType Enumeration (Office)

 Copy code hover
[image]

MsoFillType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies a shape's fill type.

Name | Value | Description
msoFillBackground | 5 | Fill is the same as the background.
msoFillGradient | 3 | Gradient fill.
msoFillMixed | -2 | Mixed fill.
msoFillPatterned | 2 | Patterned fill.
msoFillPicture | 6 | Picture fill.
msoFillSolid | 1 | Solid fill.
msoFillTextured | 4 | Textured fill.


MsoFilterComparison Enumeration (Office)

 Copy code hover
[image]

MsoFilterComparison Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies how the Column and CompareTo properties are compared for an ODSOFilter object.

Name | Value | Description
msoFilterComparisonContains | 8 | Column matches CompareTo if any part of the CompareTo string is contained in the Column value.
msoFilterComparisonEqual | 0 | Column matches CompareTo if the CompareTo value is the same as the Column value.
msoFilterComparisonGreaterThan | 3 | Column matches CompareTo if the Column value is greater than the CompareTo value.
msoFilterComparisonGreaterThanEqual | 5 | Column matches CompareTo if the Column value is greater than or equal to the CompareTo value.
msoFilterComparisonIsBlank | 6 | Column passes filter if Column is blank.
msoFilterComparisonIsNotBlank | 7 | Column passes filter if Column is blank.
msoFilterComparisonLessThan | 2 | Column matches CompareTo if the Column value is less than the CompareTo value.
msoFilterComparisonLessThanEqual | 4 | Column matches CompareTo if the Column value is less than or equal to the CompareTo value.
msoFilterComparisonNotContains | 9 | Column matches CompareTo if any part of the CompareTo string is not contained in the Column value.
msoFilterComparisonNotEqual | 1 | Column matches CompareTo if the CompareTo value is not equal to the Column value.


MsoFilterConjunction Enumeration (Office)

 Copy code hover
[image]

MsoFilterConjunction Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies how a filter criterion relates to other filter criteria. Used with the Conjunction property of the ODSOFilters object and with the Add method of the MailMergeFilters object.

Name | Value | Description
msoFilterConjunctionAnd | 0 | And conjunction.
msoFilterConjunctionOr | 1 | Or conjunction.


MsoFlipCmd Enumeration (Office)

 Copy code hover
[image]

MsoFlipCmd Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies whether a shape should be flipped horizontally or vertically.

Name | Value | Description
msoFlipHorizontal | 0 | Flip horizontally.
msoFlipVertical | 1 | Flip vertically.


MsoFontLanguageIndex Enumeration (Office)

 Copy code hover
[image]

MsoFontLanguageIndex Enumeration (Office)
Send feedback

Published: July 09, 2012

Represents one of the three language fonts contained in the ThemeFonts collection

Name | Value | Description
msoThemeComplexScript | 2 | Represents the font face for Complex Script languages. The Complex Script language collection supports Arabic, Georgian, Hebrew, Indian, Thai and Vietnamese alphabets.
msoThemeEastAsian | 3 | Represents the East Asian font face. East Asian Languages include Simplified Chinese, Traditional Chinese, Japanese, and Korean.
msoThemeLatin | 1 | Represents the Latin font face.


MsoGradientColorType Enumeration (Office)

 Copy code hover
[image]

MsoGradientColorType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type of gradient used in a shape's fill.

Name | Value | Description
msoGradientColorMixed | -2 | Mixed gradient.
msoGradientOneColor | 1 | One-color gradient.
msoGradientPresetColors | 3 | Gradient colors set according to a built-in gradient of the set defined by the msoPresetGradientType constant.
msoGradientTwoColors | 2 | Two-color gradient.


MsoGradientStyle Enumeration (Office)

 Copy code hover
[image]

MsoGradientStyle Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the style for a gradient fill.

Name | Value | Description
msoGradientDiagonalDown | 4 | Diagonal gradient moving from a top corner down to the opposite corner.
msoGradientDiagonalUp | 3 | Diagonal gradient moving from a bottom corner up to the opposite corner.
msoGradientFromCenter | 7 | Gradient running from the center out to the corners.
msoGradientFromCorner | 5 | Gradient running from a corner to the other three corners.
msoGradientFromTitle | 6 | Gradient running from the title outward.
msoGradientHorizontal | 1 | Gradient running horizontally across the shape.
msoGradientMixed | -2 | Gradient is mixed.
msoGradientVertical | 2 | Gradient running vertically down the shape.


MsoHorizontalAnchor Enumeration (Office)

 Copy code hover
[image]

MsoHorizontalAnchor Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the horizontal alignment of text in a text frame. Used with the HorizontalAnchor property of the TextFrame object.

Name | Value | Description
msoAnchorCenter | 2 | Text is centered horizontally.
msoAnchorNone | 1 | No alignment.
msoHorizontalAnchorMixed | -2 | Return value only; indicates a combination of the other states.


MsoHyperlinkType Enumeration (Office)

 Copy code hover
[image]

MsoHyperlinkType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type of hyperlink.

Name | Value | Description
msoHyperlinkInlineShape | 2 | Hyperlink applies to an inline shape. Used only with Microsoft Word.
msoHyperlinkRange | 0 | Hyperlink applies to a Range object.
msoHyperlinkShape | 1 | Hyperlink applies to a Shape object.


MsoIconType Enumeration (Office)

 Copy code hover
[image]

MsoIconType Enumeration (Office)
Send feedback

This object or member is deprecated and is not intended to be used in your code.


MsoIodGroup Enumeration (Office)

 Copy code hover
[image]

MsoIodGroup Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies constants that define the IOD (install on demand) groups.

Name | Value | Description
msoIodGroupPIAs | 0 | PIAs group.
msoIodGroupVSTOR35Mgd | 1 | VSTO 3.5 managed group.
msoIodGroupVSTOR40Mgd | 2 | VSTO 4.0 managed group.


MsoLanguageID Enumeration (Office)

 Copy code hover
[image]

MsoLanguageID Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the language identifier.

Name | Value | Description
msoLanguageIDAfrikaans | 1078 | The Afrikaans language.
msoLanguageIDAlbanian | 1052 | The Albanian language.
msoLanguageIDAmharic | 1118 | The Amharic language.
msoLanguageIDArabic | 1025 | The Arabic language.
msoLanguageIDArabicAlgeria | 5121 | The Arabic Algeria language.
msoLanguageIDArabicBahrain | 15361 | The Arabic Bahrain language.
msoLanguageIDArabicEgypt | 3073 | The Arabic Egypt language.
msoLanguageIDArabicIraq | 2049 | The Arabic Iraq language.
msoLanguageIDArabicJordan | 11265 | The Arabic Jordan language.
msoLanguageIDArabicKuwait | 13313 | The Arabic Kuwait language.
msoLanguageIDArabicLebanon | 12289 | The Arabic Lebanon language.
msoLanguageIDArabicLibya | 4097 | The Arabic Libya language.
msoLanguageIDArabicMorocco | 6145 | The Arabic Morocco language.
msoLanguageIDArabicOman | 8193 | The Arabic Oman language.
msoLanguageIDArabicQatar | 16385 | The Arabic Qatar language.
msoLanguageIDArabicSyria | 10241 | The Arabic Syria language.
msoLanguageIDArabicTunisia | 7169 | The Arabic Tunisia language.
msoLanguageIDArabicUAE | 14337 | The Arabic UAE language.
msoLanguageIDArabicYemen | 9217 | The Arabic Yemen language.
msoLanguageIDArmenian | 1067 | The Armenian language.
msoLanguageIDAssamese | 1101 | The Assamese language.
msoLanguageIDAzeriCyrillic | 2092 | The Azerbaijani Cyrillic language.
msoLanguageIDAzeriLatin | 1068 | The Azerbaijani Latin language.
msoLanguageIDBasque | 1069 | The Basque language.
msoLanguageIDBelgianDutch | 2067 | The Belgian Dutch language.
msoLanguageIDBelgianFrench | 2060 | The Belgian French language.
msoLanguageIDBengali | 1093 | The Bengali language.
msoLanguageIDBosnian | 4122 | The Bosnian language.
msoLanguageIDBosnianBosniaHerzegovinaCyrillic | 8218 | The Bosnian Bosnia Herzegovina Cyrillic language.
msoLanguageIDBosnianBosniaHerzegovinaLatin | 5146 | The Bosnian Bosnia Herzegovina Latin language.
msoLanguageIDBrazilianPortuguese | 1046 | The Portuguese (Brazil) language.
msoLanguageIDBulgarian | 1026 | The Bulgarian language.
msoLanguageIDBurmese | 1109 | The Burmese language.
msoLanguageIDByelorussian | 1059 | The Belarusian language.
msoLanguageIDCatalan | 1027 | The Catalan language.
msoLanguageIDCherokee | 1116 | The Cherokee language.
msoLanguageIDChineseHongKongSAR | 3076 | The Chinese Hong Kong SAR language.
msoLanguageIDChineseMacaoSAR | 5124 | The Chinese Macao SAR language.
msoLanguageIDChineseSingapore | 4100 | The Chinese Singapore language.
msoLanguageIDCroatian | 1050 | The Croatian language.
msoLanguageIDCzech | 1029 | The Czech language.
msoLanguageIDDanish | 1030 | The Danish language.
msoLanguageIDDivehi | 1125 | The Divehi language.
msoLanguageIDDutch | 1043 | The Dutch language.
msoLanguageIDEdo | 1126 | The Edo language.
msoLanguageIDEnglishAUS | 3081 | The English AUS language.
msoLanguageIDEnglishBelize | 10249 | The English Belize language.
msoLanguageIDEnglishCanadian | 4105 | The English Canadian language.
msoLanguageIDEnglishCaribbean | 9225 | The English Caribbean language.
msoLanguageIDEnglishIndonesia | 14345 | The English Indonesia language.
msoLanguageIDEnglishIreland | 6153 | The English Ireland language.
msoLanguageIDEnglishJamaica | 8201 | The English Jamaica language.
msoLanguageIDEnglishNewZealand | 5129 | The English NewZealand language.
msoLanguageIDEnglishPhilippines | 13321 | The English Philippines language.
msoLanguageIDEnglishSouthAfrica | 7177 | The English South Africa language.
msoLanguageIDEnglishTrinidadTobago | 11273 | The English Trinidad Tobago language.
msoLanguageIDEnglishUK | 2057 | The English UK language.
msoLanguageIDEnglishUS | 1033 | The English US language.
msoLanguageIDEnglishZimbabwe | 12297 | The English Zimbabwe language.
msoLanguageIDEstonian | 1061 | The Estonian language.
msoLanguageIDFaeroese | 1080 | The Faeroese language.
msoLanguageIDFarsi | 1065 | The Farsi language.
msoLanguageIDFilipino | 1124 | The Filipino language.
msoLanguageIDFinnish | 1035 | The Finnish language.
msoLanguageIDFrench | 1036 | The French language.
msoLanguageIDFrenchCameroon | 11276 | The French Cameroon language.
msoLanguageIDFrenchCanadian | 3084 | The French Canadian language.
msoLanguageIDFrenchCotedIvoire | 12300 | The French Coted Ivoire language.
msoLanguageIDFrenchHaiti | 15372 | The French Haiti language.
msoLanguageIDFrenchLuxembourg | 5132 | The French Luxembourg language.
msoLanguageIDFrenchMali | 13324 | The French Mali language.
msoLanguageIDFrenchMonaco | 6156 | The French Monaco language.
msoLanguageIDFrenchMorocco | 14348 | The French Morocco language.
msoLanguageIDFrenchReunion | 8204 | The French Reunion language.
msoLanguageIDFrenchSenegal | 10252 | The French Senegal language.
msoLanguageIDFrenchWestIndies | 7180 | The French West Indies language.
msoLanguageIDFranchCongoDRC | 9228 | The French Congo DRC language.
msoLanguageIDFrisianNetherlands | 1122 | The Frisian Netherlands language.
msoLanguageIDFulfulde | 1127 | The Fulfulde language.
msoLanguageIDGaelicIreland | 2108 | The Irish (Ireland) language.
msoLanguageIDGaelicScotland | 1084 | The Scottish Gaelic language.
msoLanguageIDGalician | 1110 | The Galician language.
msoLanguageIDGeorgian | 1079 | The Georgian language.
msoLanguageIDGerman | 1031 | The German language.
msoLanguageIDGermanAustria | 3079 | The German Austria language.
msoLanguageIDGermanLiechtenstein | 5127 | The German Liechtenstein language.
msoLanguageIDGermanLuxembourg | 4103 | The German Luxembourg language.
msoLanguageIDGreek | 1032 | The Greek language.
msoLanguageIDGuarani | 1140 | The Guarani language.
msoLanguageIDGujarati | 1095 | The Gujarati language.
msoLanguageIDHausa | 1128 | The Hausa language.
msoLanguageIDHawaiian | 1141 | The Hawaiian language.
msoLanguageIDHebrew | 1037 | The Hebrew language.
msoLanguageIDHindi | 1081 | The Hindi language.
msoLanguageIDHungarian | 1038 | The Hungarian language.
msoLanguageIDIbibio | 1129 | The Ibibio language.
msoLanguageIDIcelandic | 1039 | The Icelandic language.
msoLanguageIDIgbo | 1136 | The Igbo language.
msoLanguageIDIndonesian | 1057 | The Indonesian language.
msoLanguageIDInuktitut | 1117 | The Inuktitut language.
msoLanguageIDItalian | 1040 | The Italian language.
msoLanguageIDJapanese | 1041 | The Japanese language.
msoLanguageIDKannada | 1099 | The Kannada language.
msoLanguageIDKanuri | 1137 | The Kanuri language.
msoLanguageIDKashmiri | 1120 | The Kashmiri language.
msoLanguageIDKashmiriDevanagari | 2144 | The Kashmiri Devanagari language.
msoLanguageIDKazakh | 1087 | The Kazakh language.
msoLanguageIDKhmer | 1107 | The Khmer language.
msoLanguageIDKirghiz | 1088 | The Kirghiz language.
msoLanguageIDKonkani | 1111 | The Konkani language.
msoLanguageIDKorean | 1042 | The Korean language.
msoLanguageIDKyrgyz | 1088 | The Kyrgyz language.
msoLanguageIDLao | 1108 | The Lao language.
msoLanguageIDLatin | 1142 | The Latin language.
msoLanguageIDLatvian | 1062 | The Latvian language.
msoLanguageIDLithuanian | 1063 | The Lithuanian language.
msoLanguageIDMacedoninanFYROM | 1071 | The Macedonian FYROM language.
msoLanguageIDMalayalam | 1100 | The Malayalam language.
msoLanguageIDMalayBruneiDarussalam | 2110 | The Malay Brunei Darussalam language.
msoLanguageIDMalaysian | 1086 | The Malaysian language.
msoLanguageIDMaltese | 1082 | The Maltese language.
msoLanguageIDManipuri | 1112 | The Manipuri language.
msoLanguageIDMaori | 1153 | The Maori language.
msoLanguageIDMarathi | 1102 | The Marathi language.
msoLanguageIDMexicanSpanish | 2058 | The Mexican Spanish language.
msoLanguageIDMixed | -2 | The Mixed language.
msoLanguageIDMongolian | 1104 | The Mongolian language.
msoLanguageIDNepali | 1121 | The Nepali language.
msoLanguageIDNone | 0 | No language specified.
msoLanguageIDNoProofing | 1024 | No proofing.
msoLanguageIDNorwegianBokmol | 1044 | The Norwegian Bokmol language.
msoLanguageIDNorwegianNynorsk | 2068 | The Norwegian Nynorsk language.
msoLanguageIDOriya | 1096 | The Odia language.
msoLanguageIDOromo | 1138 | The Oromo language.
msoLanguageIDPashto | 1123 | The Pashto language.
msoLanguageIDPolish | 1045 | The Polish language.
msoLanguageIDPortuguese | 2070 | The Portuguese language.
msoLanguageIDPunjabi | 1094 | The Punjabi language.
msoLanguageIDQuechuaBolivia | 1131 | The Quechua Bolivia language.
msoLanguageIDQuechuaEcuador | 2155 | The Quechua Ecuador language.
msoLanguageIDQuechuaPeru | 3179 | The Quechua Peru language.
msoLanguageIDRhaetoRomanic | 1047 | The Rhaeto Romanic language.
msoLanguageIDRomanian | 1048 | The Romanian language.
msoLanguageIDRomanianMoldova | 2072 | The Romanian Moldova language.
msoLanguageIDRussian | 1049 | The Russian language.
msoLanguageIDRussianMoldova | 2073 | The Russian Moldova language.
msoLanguageIDSamiLappish | 1083 | The Sami Lappish language.
msoLanguageIDSanskrit | 1103 | The Sanskrit language.
msoLanguageIDSepedi | 1132 | The Sepedi language.
msoLanguageIDSerbianBosniaHerzegovinaCyrillic | 7194 | The Serbian Bosnia Herzegovina Cyrillic language.
msoLanguageIDSerbianBosniaHerzegovinaLatin | 6170 | The Serbian Bosnia Herzegovina Latin language.
msoLanguageIDSerbianCyrillic | 3098 | The Serbian Cyrillic language.
msoLanguageIDSerbianLatin | 2074 | The Serbian Latin language.
msoLanguageIDSesotho | 1072 | The Sesotho language.
msoLanguageIDSimplifiedChinese | 2052 | The Simplified Chinese language.
msoLanguageIDSindhi | 1113 | The Sindhi language.
msoLanguageIDSindhiPakistan | 2137 | The Sindhi Pakistan language.
msoLanguageIDSinhalese | 1115 | The Sinhalese language.
msoLanguageIDSlovak | 1051 | The Slovak language.
msoLanguageIDSlovenian | 1060 | The Slovenian language.
msoLanguageIDSomali | 1143 | The Somali language.
msoLanguageIDSorbian | 1070 | The Sorbian language.
msoLanguageIDSpanish | 1034 | The Spanish language.
msoLanguageIDSpanishArgentina | 11274 | The Spanish Argentina language.
msoLanguageIDSpanishBolivia | 16394 | The Spanish Bolivia language.
msoLanguageIDSpanishChile | 13322 | The Spanish Chile language.
msoLanguageIDSpanishColombia | 9226 | The Spanish Colombia language.
msoLanguageIDSpanishCostaRica | 5130 | The Spanish Costa Rica language.
msoLanguageIDSpanishDominicanRepublic | 7178 | The Spanish Dominican Republic language.
msoLanguageIDSpanishEcuador | 12298 | The Spanish Ecuador language.
msoLanguageIDSpanishElSalvador | 17418 | The Spanish El Salvador language.
msoLanguageIDSpanishGuatemala | 4106 | The Spanish Guatemala language.
msoLanguageIDSpanishHonduras | 18442 | The Spanish Honduras language.
msoLanguageIDSpanishModernSort | 3082 | The Spanish Modern Sort language.
msoLanguageIDSpanishNicaragua | 19466 | The Spanish Nicaragua language.
msoLanguageIDSpanishPanama | 6154 | The Spanish Panama language.
msoLanguageIDSpanishParaguay | 15370 | The Spanish Paraguay language.
msoLanguageIDSpanishPeru | 10250 | The Spanish Peru language.
msoLanguageIDSpanishPuertoRico | 20490 | The Spanish Puerto Rico language.
msoLanguageIDSpanishUruguay | 14346 | The Spanish Uruguay language.
msoLanguageIDSpanishVenezuela | 8202 | The Spanish Venezuela language.
msoLanguageIDSutu | 1072 | The Sutu language.
msoLanguageIDSwahili | 1089 | The Swahili language.
msoLanguageIDSwedish | 1053 | The Swedish language.
msoLanguageIDSwedishFinland | 2077 | The Swedish Finland language.
msoLanguageIDSwissFrench | 4108 | The Swiss French language.
msoLanguageIDSwissGerman | 2055 | The Swiss German language.
msoLanguageIDSwissItalian | 2064 | The Swiss Italian language.
msoLanguageIDSyriac | 1114 | The Syriac language.
msoLanguageIDTajik | 1064 | The Tajik language.
msoLanguageIDTamazight | 1119 | The Tamazight language.
msoLanguageIDTamazightLatin | 2143 | The Tamazight Latin language.
msoLanguageIDTamil | 1097 | The Tamil language.
msoLanguageIDTatar | 1092 | The Tatar language.
msoLanguageIDTelugu | 1098 | The Telugu language.
msoLanguageIDThai | 1054 | The Thai language.
msoLanguageIDTibetan | 1105 | The Tibetan language.
msoLanguageIDTigrignaEritrea | 2163 | The Tigrigna Eritrea language.
msoLanguageIDTigrignaEthiopic | 1139 | The Tigrigna Ethiopic language.
msoLanguageIDTraditionalChinese | 1028 | The Traditional Chinese language.
msoLanguageIDTsonga | 1073 | The Tsonga language.
msoLanguageIDTswana | 1074 | The Tswana language.
msoLanguageIDTurkish | 1055 | The Turkish language.
msoLanguageIDTurkmen | 1090 | The Turkmen language.
msoLanguageIDUkrainian | 1058 | The Ukrainian language.
msoLanguageIDUrdu | 1056 | The Urdu language.
msoLanguageIDUzbekCyrillic | 2115 | The Uzbek Cyrillic language.
msoLanguageIDUzbekLatin | 1091 | The Uzbek Latin language.
msoLanguageIDVenda | 1075 | The Venda language.
msoLanguageIDVietnamese | 1066 | The Vietnamese language.
msoLanguageIDWelsh | 1106 | The Welsh language.
msoLanguageIDXhosa | 1076 | The Xhosa language.
msoLanguageIDYi | 1144 | The Yi language.
msoLanguageIDYiddish | 1085 | The Yiddish language.
msoLanguageIDYoruba | 1130 | The Yoruba language.
msoLanguageIDZulu | 1077 | The Zulu language.


MsoLightRigType Enumeration (Office)

 Copy code hover
[image]

MsoLightRigType Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the effects lighting for an object.

Name | Value | Description
msoLightRigBalanced | 14 | Specifies the Balanced effect.
msoLightRigBrightRoom | 27 | Specifies the BrightRoom effect.
msoLightRigChilly | 22 | Specifies the Chilly effect.
msoLightRigContrasting | 18 | Specifies the Contrasting effect.
msoLightRigFlat | 24 | Specifies the Flat effect.
msoLightRigFlood | 17 | Specifies the Flood effect.
msoLightRigFreezing | 23 | Specifies the Freezing effect.
msoLightRigGlow | 26 | Specifies the Glow effect.
msoLightRigHarsh | 16 | Specifies the Harsh effect.
msoLightRigLegacyFlat1 | 1 | Specifies the LegacyFlat1 effect.
msoLightRigLegacyFlat2 | 2 | Specifies the LegacyFlat2 effect.
msoLightRigLegacyFlat3 | 3 | Specifies the LegacyFlat3 effect.
msoLightRigLegacyFlat4 | 4 | Specifies the LegacyFlat4 effect.
msoLightRigLegacyHarsh1 | 9 | Specifies the LegacyHarsh1 effect.
msoLightRigLegacyHarsh2 | 10 | Specifies the LegacyHarsh2 effect.
msoLightRigLegacyHarsh3 | 11 | Specifies the LegacyHarsh3 effect.
msoLightRigLegacyHarsh4 | 12 | Specifies the LegacyHarsh4 effect.
msoLightRigLegacyNormal1 | 5 | Specifies the LegacyNormal1 effect.
msoLightRigLegacyNormal2 | 6 | Specifies the LegacyNormal2 effect.
msoLightRigLegacyNormal3 | 7 | Specifies the LegacyNormal3 effect.
msoLightRigLegacyNormal4 | 8 | Specifies the LegacyNormal4 effect.
msoLightRigMixed | -2 | Specifies the Mixed effect.
msoLightRigMorning | 19 | Specifies the Morning effect.
msoLightRigSoft | 15 | Specifies the Soft effect.
msoLightRigSunrise | 20 | Specifies the Sunrise effect.
msoLightRigSunset | 21 | Specifies the Sunset effect.
msoLightRigThreePoint | 13 | Specifies the ThreePoint effect.
msoLightRigTwoPoint | 25 | Specifies the TwoPoint effect.


MsoLineCapStyle Enumeration (Office)

 Copy code hover
[image]

MsoLineCapStyle Enumeration (Office)
Send feedback

Specifies the type of line cap.

Version information

Version Added: Office 2013

Members

Name | Value | Description
msoLineCapFlat | 3 | Specifies a flat line cap.
msoLineCapMixed | -2 | Specifies a mixture of line caps.
msoLineCapRound | 2 | Specifies a rounded line cap.
msoLineCapSquare | 1 | Speciifes a squared-off line cap.
msoLineCapFlat | 3 |
msoLineCapMixed | -2 |
msoLineCapRound | 2 |
msoLineCapSquare | 1 |


MsoLineDashStyle Enumeration (Office)

 Copy code hover
[image]

MsoLineDashStyle Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the dash style for a line.

Name | Value | Description
msoLineDash | 4 | Line consists of dashes only.
msoLineDashDot | 5 | Line is a dash-dot pattern.
msoLineDashDotDot | 6 | Line is a dash-dot-dot pattern.
msoLineDashStyleMixed | -2 | Not supported.
msoLineLongDash | 7 | Line consists of long dashes.
msoLineLongDashDot | 8 | Line is a long dash-dot pattern.
msoLineRoundDot | 3 | Line is made up of round dots.
msoLineSolid | 1 | Line is solid.
msoLineSquareDot | 2 | Line is made up of square dots.


MsoLineFillType Enumeration (Office)

 Copy code hover
[image]

MsoLineFillType Enumeration (Office)
Send feedback

Specifies the type of fill for a line.

Version information

Version Added: Office 2013

Members

Name | Value | Description
msoLineFillBackground | 5 | Specifies the same fill as the background
msoLineFillGradient | 3 | Specifies a gradient line fill.
msoLineFillMixed | -2 | Specifies a mixture of line fill types.
msoLineFillNone | 0 | No line fill.
msoLineFillPatterned | 2 | Specifies a pattern line fill.
msoLineFillPicture | 6 | Specifies a picture line fill.
msoLineFillSolid | 1 | Specifies a solid color line fill.
msoLineFillTextured | 4 | Specifies a textured line fill.
msoLineFillBackground | 5 |
msoLineFillGradient | 3 |
msoLineFillMixed | -2 |
msoLineFillNone | 0 |
msoLineFillPatterned | 2 |
msoLineFillPicture | 6 |
msoLineFillSolid | 1 |
msoLineFillTextured | 4 |


MsoLineJoinStyle Enumeration (Office)

 Copy code hover
[image]

MsoLineJoinStyle Enumeration (Office)
Send feedback

Specifies the type of join where two lines connect.

Version information

Version Added: Office 2013

Members

Name | Value | Description
msoLineJoinBevel | 2 | Specifies a beveled join.
msoLineJoinMiter | 3 | Specifies a mitered join.
msoLineJoinMixed | -2 | Specifies a mixture of join types.
msoLineJoinRound | 1 | Specifies a rounded join.
msoLineJoinBevel | 2 |
msoLineJoinMiter | 3 |
msoLineJoinMixed | -2 |
msoLineJoinRound | 1 |


MsoLineStyle Enumeration (Office)

 Copy code hover
[image]

MsoLineStyle Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the style for a line.

Name | Value | Description
msoLineSingle | 1 | Single line.
msoLineStyleMixed | -2 | Not supported.
msoLineThickBetweenThin | 5 | Thick line with a thin line on each side.
msoLineThickThin | 4 | Thick line next to thin line. For horizontal lines, thick line is above thin line. For vertical lines, thick line is to the left of the thin line.
msoLineThinThick | 3 | Thick line next to thin line. For horizontal lines, thick line is below thin line. For vertical lines, thick line is to the right of the thin line.
msoLineThinThin | 2 | Two thin lines.


MsoMenuAnimation Enumeration (Office)

 Copy code hover
[image]

MsoMenuAnimation Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies animation style for Microsoft Office command bars.

Name | Value | Description
msoMenuAnimationNone | 0 | No animation.
msoMenuAnimationRandom | 1 | Random animation.
msoMenuAnimationSlide | 3 | Menus slide into view.
msoMenuAnimationUnfold | 2 | Menus unfold into view.


MsoMergeCmd Enumeration (Office)

 Copy code hover
[image]

MsoMergeCmd Enumeration (Office)
Send feedback

Specifies the output of a merge shapes operation.

Version information

Version Added: Office 2013

Members

Name | Value | Description
msoMergeCombine | 2 | Creates a new shape from selected shapes. If the selected shapes overlap, the area where they overlap is cut out, or discarded.
msoMergeFragment | 5 | Breaks a shape into smaller parts or create new shapes from intersecting lines or from shapes that overlap.
msoMergeIntersect | 3 | Forms a new closed shape from the area where selected shapes overlap, eliminating non-overlapping areas.
msoMergeSubtract | 4 | Creates a new shape by subtracting from the primary selection the areas where subsequent selections overlap.
msoMergeUnion | 1 | Creates a new shape from the perimeter of two or more overlapping shapes. The new shape is a set of all the points from the original shapes.
msoMergeCombine | 2 |
msoMergeFragment | 5 |
msoMergeIntersect | 3 |
msoMergeSubtract | 4 |
msoMergeUnion | 1 |


MsoMetaPropertyType Enumeration (Office)

 Copy code hover
[image]

MsoMetaPropertyType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the metadata property type.

Name | Value | Description
msoMetaPropertyTypeBoolean | 1 | Represents a Boolean value.
msoMetaPropertyTypeCalculated | 3 | Represents a calculated value.
msoMetaPropertyTypeChoice | 2 | Represents a value from one or more choices.
msoMetaPropertyTypeComputed | 4 | Represents a computed value.
msoMetaPropertyTypeCurrency | 5 | Represents a Currency value
msoMetaPropertyTypeDateTime | 6 | Represents a DateTime value.
msoMetaPropertyTypeFillInChoice | 7 | Represents a value from two or more choices that is written-in by the user.
msoMetaPropertyTypeGuid | 8 | Represents a GUID value.
msoMetaPropertyTypeInteger | 9 | Represents an Integer value.
msoMetaPropertyTypeLookup | 10 | Represents a value used to lookup another value.
msoMetaPropertyTypeMax | 19 | Represents the maximum value for a range.
msoMetaPropertyTypeMultiChoice | 12 | Represents a collection of choices.
msoMetaPropertyTypeMultiChoiceFillIn | 13 | Represents a collection of choices that require the user to write-in a value.
msoMetaPropertyTypeMultiChoiceLookup | 11 | Represents a collection of choices used to lookup another value.
msoMetaPropertyTypeNote | 14 | Represents a value of one or more sentences.
msoMetaPropertyTypeNumber | 15 | Represents a generic number data type.
msoMetaPropertyTypeText | 16 | Represents a Text value.
msoMetaPropertyTypeUnknown | 0 | Represents an unknown value.
msoMetaPropertyTypeUrl | 17 | Represents a URL.
msoMetaPropertyTypeUser | 18 | Represents a category of user.


MsoMixedType Enumeration (Office)

 Copy code hover
[image]

MsoMixedType Enumeration (Office)
Send feedback

Published: July 09, 2012

This enumeration has been deprecated and should not be used.

Name | Value | Description
msoIntegerMixed | 32768 | Internal use only.
msoSingleMixed | -2147483648 | Internal use only.


MsoModeType Enumeration (Office)

 Copy code hover
[image]

MsoModeType Enumeration (Office)
Send feedback

This object or member is deprecated and is not intended to be used in your code.


MsoMoveRow Enumeration (Office)

 Copy code hover
[image]

MsoMoveRow Enumeration (Office)
Send feedback

Published: July 09, 2012

This enumeration has been deprecated and should not be used.

Name | Value | Description
msoMoveRowFirst | -4 | Internal use only.
msoMoveRowNbr | -1 | Internal use only.
msoMoveRowNext | -2 | Internal use only.
msoMoveRowPrev | -3 | Internal use only.


MsoNumberedBulletStyle Enumeration (Office)

 Copy code hover
[image]

MsoNumberedBulletStyle Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies numbered bullet styles.

Version Information

Version Added: Office Core 2007

Name | Value | Description
msoBulletAlphaLCParenBoth | 8 | Lowercase alphabetical bullet with opening and closing parentheses.
msoBulletAlphaLCParenRight | 9 | Lowercase alphabetical bullet with closing parenthesis.
msoBulletAlphaLCPeriod | 0 | Lowercase alphabetical bullet with period.
msoBulletAlphaUCParenBoth | 10 | Uppercase alphabetical bullet with opening and closing parentheses.
msoBulletAlphaUCParenRight | 11 | Uppercase alphabetical bullet with closing parenthesis.
msoBulletAlphaUCPeriod | 1 | Uppercase alphabetical bullet with period.
msoBulletArabicAbjadDash | 24 | Arabic Abjad bullet with a dash.
msoBulletArabicAlphaDash | 23 | Arabic alphabetical bullet with a dash.
msoBulletArabicDBPeriod | 29 | Arabic DB bullet with period.
msoBulletArabicDBPlain | 28 | Plain Arabic DB bullet.
msoBulletArabicParenBoth | 12 | Arabic bullet with opening and closing parentheses.
msoBulletArabicParenRight | 2 | Arabic bullet with closing parenthesis.
msoBulletArabicPeriod | 3 | Arabic bullet with period.
msoBulletArabicPlain | 13 | Plain Arabic bullet.
msoBulletCircleNumDBPlain | 18 | Circled number bullet.
msoBulletCircleNumWDBlackPlain | 20 | Circled number WD black bullet.
msoBulletCircleNumWDWhitePlain | 19 | Circled number WD white bullet.
msoBulletHebrewAlphaDash | 25 | Hebrew alphabetical bullet with dash.
msoBulletHindiAlpha1Period | 40 | Hindi alphabetical bullet 1 with period.
msoBulletHindiAlphaPeriod | 36 | Hindi alphabetical bullet with period.
msoBulletHindiNumParenRight | 39 | Hindi numbered bullet with closing parenthesis.
msoBulletHindiNumPeriod | 37 | Hindi numbered bullet with period.
msoBulletKanjiKoreanPeriod | 27 | Korean Kanji bullet with period.
msoBulletKanjiKoreanPlain | 26 | Korean Kanji bullet.
msoBulletKanjiSimpChinDBPeriod | 38 | Simplified Chinese Kanji bulllet with period.
msoBulletRomanLCParenBoth | 4 | Lowercase roman bullet with opening and closing parentheses.
msoBulletRomanLCParenRight | 5 | Lowercase roman bullet with closing parenthesis.
msoBulletRomanLCPeriod | 6 | Lowercase roman bullet with period.
msoBulletRomanUCParenBoth | 14 | Uppercase roman bullet with opening and closing parentheses.
msoBulletRomanUCParenRight | 15 | Uppercase roman bullet with closing parenthesis.
msoBulletRomanUCPeriod | 7 | Uppercase roman bullet with period.
msoBulletSimpChinPeriod | 17 | Simplified Chinese bulllet with period.
msoBulletSimpChinPlain | 16 | Simplified Chinese bullet.
msoBulletStyleMixed | -2 | Return value only; indicates a combination of the other states.
msoBulletThaiAlphaParenBoth | 32 | Thai alphabetical bullet with opening and closing parentheses.
msoBulletThaiAlphaParenRight | 31 | Thai alphabetical bullet with closing parenthesis.
msoBulletThaiAlphaPeriod | 30 | Thai alphabetical bullet with period.
msoBulletThaiNumParenBoth | 35 | Thai numerical bullet with opening and closing parentheses.
msoBulletThaiNumParenRight | 34 | Thai numerical bullet with closing parenthesis.
msoBulletThaiNumPeriod | 33 | Thai numerical bullet with period.
msoBulletTradChinPeriod | 22 | Traditional Chinese bulllet with period.
msoBulletTradChinPlain | 21 | Traditional Chinese bulllet.


MsoOLEMenuGroup Enumeration (Office)

 Copy code hover
[image]

MsoOLEMenuGroup Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the menu group that a command bar pop-up control belongs to when the menu groups of the OLE server are merged with the menu groups of an OLE client (that is, when an object of the container application type is embedded in another application).

Name | Value | Description
msoOLEMenuGroupContainer | 2 | Container menu.
msoOLEMenuGroupEdit | 1 | Edit menu.
msoOLEMenuGroupFile | 0 | File menu.
msoOLEMenuGroupHelp | 5 | Help menu.
msoOLEMenuGroupNone | -1 | Pop-up control is not merged.
msoOLEMenuGroupObject | 3 | Object menu.
msoOLEMenuGroupWindow | 4 | Window menu.


MsoOrgChartLayoutType Enumeration (Office)

 Copy code hover
[image]

MsoOrgChartLayoutType Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates how to format the child nodes in an organization chart.

Name | Value | Description
msoOrgChartLayoutBothHanging | 2 | Places child nodes vertically below the parent node on both the left and the right side.
msoOrgChartLayoutLeftHanging | 3 | Places child nodes vertically below the parent node on the left side.
msoOrgChartLayoutMixed | -2 | Return value for a parent node that has children formatted using more than one MsoOrgChartLayoutType.
msoOrgChartLayoutRightHanging | 4 | Places child nodes vertically below the parent node on the right side.
msoOrgChartLayoutStandard | 1 | Places child nodes horizontally below the parent node.


MsoOrgChartOrientation Enumeration (Office)

 Copy code hover
[image]

MsoOrgChartOrientation Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies orientation of an organization chart.

Version Information

Version Added: Office System 2003

Name | Value | Description
msoOrgChartOrientationMixed | -2 | Mixed orientation.
msoOrgChartOrientationVertical | 1 | Vertical orientation.


MsoOrientation Enumeration (Office)

 Copy code hover
[image]

MsoOrientation Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies orientation of an object when it is displayed or printed.

Name | Value | Description
msoOrientationHorizontal | 1 | Horizontal (landscape) orientation.
msoOrientationMixed | -2 | Mixed orientation.
msoOrientationVertical | 2 | Vertical (portrait) orientation.


MsoParagraphAlignment Enumeration (Office)

 Copy code hover
[image]

MsoParagraphAlignment Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies paragraph alignment for a text block.

Name | Value | Description
msoAlignCenter | 1 | Specifies that the center of each line of text is aligned to the midpoint of the right and left text box margins, and the left and right edges of each line are ragged.
msoAlignDistribute | 4 | Specifies that the first and last characters of each line (except the last) are aligned to the left and right margins, and lines are filled by adding or subtracting the same amount from each character. The last line of the paragraph is aligned to the left margin if text direction is left-to-right, or to the right margin if text direction is right-to-left.
msoAlignJustify | 3 | Specifies that the first and last characters of each line (except the last) are aligned to the left and right margins, and lines are filled by adding or subtracting space between and within words. The last line of the paragraph is aligned to the left margin if text direction is left-to-right, or to the right margin if text direction is right-to-left.
msoAlignJustifyLow | 6 | Specifies the alignment or adjustment of kashida length in Arabic text. Kashida are special characters used to extend the joiner between two Arabic characters.
msoAlignLeft | 0 | Specifies that the leftmost character of each line is aligned to the left margin, and the right edge of each line is ragged. This is the default alignment for paragraphs with left-to-right text direction.
msoAlignMixed | -2 | Use a combination of alignment styles.
msoAlignRight | 2 | Specifies that the rightmost character of each line is aligned to the right margin, and the left edge of each line is ragged. This is the default alignment for paragraphs with right-to-left text direction.
msoAlignThaiDistribute | 5 | Specifies that the first and last characters of each line (except the last) are aligned to the left and right margins, and lines are filled by adding or subtracting space between (but not within) words. The last line of the paragraph is aligned to the left margin.


MsoPathFormat Enumeration (Office)

 Copy code hover
[image]

MsoPathFormat Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the format of a file or folder path.

Name | Value | Description
msoPathType1 | 1 | Represents the Type1 format.
msoPathType2 | 2 | Represents the Type2 format.
msoPathType3 | 3 | Represents the Type3 format.
msoPathType4 | 4 | Represents the Type4 format.
msoPathType5 | 5 | Represents the Type5 format.
msoPathType6 | 6 | Represents the Type6 format.
msoPathType7 | 7 | Represents the Type7 format.
msoPathType8 | 8 | Represents the Type8 format.
msoPathType9 | 9 | Represents the Type9 format.
msoPathTypeMixed | -2 | Represents a mixed format.
msoPathTypeNone | 0 | Represents no format.


MsoPatternType Enumeration (Office)

 Copy code hover
[image]

MsoPatternType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the fill pattern used in a shape.

Name | Value | Description
msoPattern10Percent | 2 | 10% of the foreground color.
msoPattern20Percent | 3 | 20% of the foreground color.
msoPattern25Percent | 4 | 25% of the foreground color.
msoPattern30Percent | 5 | 30% of the foreground color.
msoPattern40Percent | 6 | 40% of the foreground color.
msoPattern50Percent | 7 | 50% of the foreground color.
msoPattern5Percent | 1 | 5% of the foreground color.
msoPattern60Percent | 8 | 60% of the foreground color.
msoPattern70Percent | 9 | 70% of the foreground color.
msoPattern75Percent | 10 | 75% of the foreground color.
msoPattern80Percent | 11 | 80% of the foreground color.
msoPattern90Percent | 12 | 90% of the foreground color.
msoPatternCross | 51 | Cross
msoPatternDarkDownwardDiagonal | 15 | Dark Downward Diagonal
msoPatternDarkHorizontal | 13 | Dark Horizontal
msoPatternDarkUpwardDiagonal | 16 | Dark Upward Diagonal
msoPatternDarkVertical | 14 | Dark Vertical
msoPatternDashedDownwardDiagonal | 28 | Dashed Downward Diagonal
msoPatternDashedHorizontal | 32 | Dashed Horizontal
msoPatternDashedUpwardDiagonal | 27 | Dashed Upward Diagonal
msoPatternDashedVertical | 31 | Dashed Vertical
msoPatternDiagonalBrick | 40 | Diagonal Brick
msoPatternDiagonalCross | 54 | Diagonal Cross
msoPatternDivot | 46 | Pattern Divot
msoPatternDottedDiamond | 24 | Dotted Diamond
msoPatternDottedGrid | 45 | Dotted Grid
msoPatternDownwardDiagonal | 52 | Downward Diagonal
msoPatternHorizontal | 49 | Horizontal
msoPatternHorizontalBrick | 35 | Horizontal Brick
msoPatternLargeCheckerBoard | 36 | Large Checker Board
msoPatternLargeConfetti | 33 | Large Confetti
msoPatternLargeGrid | 34 | Large Grid
msoPatternLightDownwardDiagonal | 21 | Light Downward Diagonal
msoPatternLightHorizontal | 19 | Light Horizontal
msoPatternLightUpwardDiagonal | 22 | Light Upward Diagonal
msoPatternLightVertical | 20 | Light Vertical
msoPatternMixed | -2 | Mixed pattern
msoPatternNarrowHorizontal | 30 | Narrow Horizontal
msoPatternNarrowVertical | 29 | Narrow Vertical
msoPatternOutlinedDiamond | 41 | Outlined Diamond
msoPatternPlaid | 42 | Plaid
msoPatternShingle | 47 | Shingle
msoPatternSmallCheckerBoard | 17 | Small Checker Board
msoPatternSmallConfetti | 37 | Small Confetti
msoPatternSmallGrid | 23 | Small Grid
msoPatternSolidDiamond | 39 | Solid Diamond
msoPatternSphere | 43 | Sphere
msoPatternTrellis | 18 | Trellis
msoPatternUpwardDiagonal | 53 | Upward Diagonal
msoPatternVertical | 50 | Vertical
msoPatternWave | 48 | Wave
msoPatternWeave | 44 | Weave
msoPatternWideDownwardDiagonal | 25 | Wide Downward Diagonal
msoPatternWideUpwardDiagonal | 26 | Wide Upward Diagonal
msoPatternZigZag | 38 | Zig Zag


MsoPermission Enumeration (Office)

 Copy code hover
[image]

MsoPermission Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies an Information Rights Management (IRM) permission type for a document.

Name | Value | Description
msoPermissionChange | 15 | Permission to change.
msoPermissionEdit | 2 | Permission to edit.
msoPermissionExtract | 8 | Permission to extract.
msoPermissionFullControl | 64 | Full control permissions.
msoPermissionObjModel | 32 | Permission to access the object model programmatically.
msoPermissionPrint | 16 | Permission to print.
msoPermissionRead | 1 | Permission to read.
msoPermissionSave | 4 | Permission to save.
msoPermissionView | 1 | Permission to view.


MsoPickerField Enumeration (Office)

 Copy code hover
[image]

MsoPickerField Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies contact-picker field types.

Name | Value | Description
msoPickerFieldUnknown | 0 | An unknown type of field.
msoPickerFieldDateTime | 1 | A DateTime field.
msoPickerFieldNumber | 2 | A number field.
msoPickerFieldText | 3 | A text field.
msoPickerFieldUser | 4 | A user or group field.
msoPickerFieldMax | 5 | The sentinel value of the enumeration.


MsoPictureColorType Enumeration (Office)

 Copy code hover
[image]

MsoPictureColorType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the color transformation applied to a picture.

Name | Value | Description
msoPictureAutomatic | 1 | Default color transformation.
msoPictureBlackAndWhite | 3 | Black-and-white transformation.
msoPictureGrayscale | 2 | Grayscale transformation.
msoPictureMixed | -2 | Mixed transformation.
msoPictureWatermark | 4 | Watermark transformation.


MsoPictureCompress Enumeration (Office)

 Copy code hover
[image]

MsoPictureCompress Enumeration (Office)
Send feedback

Specifies whether a picture will be compressed or not when inserted into a file.

Name | Value | Description
msoPictureCompressDocDefault | -1 | The picture is compressed or not depending on the settings for the document.
msoPictureCompressFalse | 0 | The picture is not compressed.
msoPictureCompressTrue | 1 | The picture will be compressed.


MsoPictureEffectType Enumeration (Office)

 Copy code hover
[image]

MsoPictureEffectType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies constants that define the types of picture effects.

Name | Value | Description
msoEffectBackgroundRemoval | 1 | Background removal effect.
msoEffectBlur | 2 | Blur effect.
msoEffectBrightnessContrast | 3 | Brightness contrast effect.
msoEffectCement | 4 | Cement effect.
msoEffectChalkSketch | 5 | Chalk sketch effect.
msoEffectColorTemperature | 6 | Color temperature effect.
msoEffectCrisscrossEtching | 7 | Crisscross etching effect.
msoEffectCutout | 8 | Cutout effect.
msoEffectFilmGrain | 9 | Film grain effect.
msoEffectGlass | 10 | Glass effect.
msoEffectGlowDiffused | 11 | Diffused glow effect.
msoEffectGlowEdges | 12 | Glow edges effect.
msoEffectLightScreen | 13 | Light screen effect.
msoEffectLineDrawing | 14 | Line drawing effect.
msoEffectMarker | 15 | Marker effect.
msoEffectMosiacBubbles | 16 | Mosaic bubbles.
msoEffectNone | 17 | No effect.
msoEffectPaintBrush | 18 | Paintbrush effect.
msoEffectPaintStrokes | 19 | Paint strokes effect.
msoEffectPastelsSmooth | 20 | Smooth pastel effect.
msoEffectPencilGrayscale | 21 | Pencil greyscale effect.
msoEffectPencilSketch | 22 | Pencil sketch effect.
msoEffectPhotocopy | 23 | Photocopy effect.
msoEffectPlasticWrap | 24 | Plastic wrap effect.
msoEffectSaturation | 25 | Saturation effect.
msoEffectSharpenSoften | 26 | Sharpen soften effect.
msoEffectTexturizer | 27 | Texturizer effect.
msoEffectWatercolorSponge | 28 | Watercolor sponge effect.


MsoPresetCamera Enumeration (Office)

 Copy code hover
[image]

MsoPresetCamera Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the effects camera type used by the specified object.

Name | Value | Description
msoCameraIsometricBottomDown | 23 | Specifies Isometric Bottom Down.
msoCameraIsometricBottomUp | 22 | Specifies Isometric Bottom Up.
msoCameraIsometricLeftDown | 25 | Specifies Isometric Left Down.
msoCameraIsometricLeftUp | 24 | Specifies Isometric Left Up.
msoCameraIsometricOffAxis1Left | 28 | Specifies Isometric OffAxis1 Left.
msoCameraIsometricOffAxis1Right | 29 | Specifies Isometric OffAxis1 Right.
msoCameraIsometricOffAxis1Top | 30 | Specifies Isometric OffAxis1 Top.
msoCameraIsometricOffAxis2Left | 31 | Specifies Isometric OffAxis2 Left.
msoCameraIsometricOffAxis2Right | 32 | Specifies Isometric OffAxis2 Right.
msoCameraIsometricOffAxis2Top | 33 | Specifies Isometric OffAxis2 Top.
msoCameraIsometricOffAxis3Bottom | 36 | Specifies Isometric OffAxis3 Bottom.
msoCameraIsometricOffAxis3Left | 34 | Specifies Isometric OffAxis3 Left.
msoCameraIsometricOffAxis3Right | 35 | Specifies Isometric OffAxis3 Right.
msoCameraIsometricOffAxis4Bottom | 39 | Specifies Isometric OffAxis4 Bottom.
msoCameraIsometricOffAxis4Left | 37 | Specifies Isometric OffAxis4 Left.
msoCameraIsometricOffAxis4Right | 38 | Specifies Isometric OffAxis4 Right.
msoCameraIsometricRightDown | 27 | Specifies Isometric Right Down.
msoCameraIsometricRightUp | 26 | Specifies Isometric Right Up.
msoCameraIsometricTopDown | 21 | Specifies Isometric Top Down.
msoCameraIsometricTopUp | 20 | Specifies Isometric Top Up.
msoCameraLegacyObliqueBottom | 8 | Specifies Legacy Oblique Bottom.
msoCameraLegacyObliqueBottomLeft | 7 | Specifies Legacy Oblique Lower Left.
msoCameraLegacyObliqueBottomRight | 9 | Specifies Legacy Oblique Lower Right.
msoCameraLegacyObliqueFront | 5 | Specifies Legacy Oblique Front.
msoCameraLegacyObliqueLeft | 4 | Specifies Legacy Oblique Left.
msoCameraLegacyObliqueRight | 6 | Specifies Legacy Oblique Right.
msoCameraLegacyObliqueTop | 2 | Specifies Legacy Oblique Top.
msoCameraLegacyObliqueTopLeft | 1 | Specifies Legacy Oblique Upper Left.
msoCameraLegacyObliqueTopRight | 3 | Specifies Legacy Oblique Upper Right.
msoCameraLegacyPerspectiveBottom | 17 | Specifies Legacy Perspective Bottom.
msoCameraLegacyPerspectiveBottomLeft | 16 | Specifies Legacy Perspective Lower Left.
msoCameraLegacyPerspectiveBottomRight | 18 | Specifies Legacy Perspective Lower Right.
msoCameraLegacyPerspectiveFront | 14 | Specifies Legacy Perspective Front.
msoCameraLegacyPerspectiveLeft | 13 | Specifies Legacy Perspective Left.
msoCameraLegacyPerspectiveRight | 15 | Specifies Legacy Perspective Right.
msoCameraLegacyPerspectiveTop | 11 | Specifies Legacy Perspective Top.
msoCameraLegacyPerspectiveTopLeft | 10 | Specifies Legacy Perspective Upper Left.
msoCameraLegacyPerspectiveTopRight | 12 | Specifies Legacy Perspective Upper Right.
msoCameraObliqueBottom | 46 | Specifies Oblique Bottom.
msoCameraObliqueBottomLeft | 45 | Specifies Oblique Lower Left.
msoCameraObliqueBottomRight | 47 | Specifies Oblique Lower Right.
msoCameraObliqueLeft | 43 | Specifies Oblique Left.
msoCameraObliqueRight | 44 | Specifies Oblique Right.
msoCameraObliqueTop | 41 | Specifies Oblique Top.
msoCameraObliqueTopLeft | 40 | Specifies Oblique Upper Left.
msoCameraObliqueTopRight | 42 | Specifies Oblique Upper Right.
msoCameraOrthographicFront | 19 | Specifies Orthographic Front.
msoCameraPerspectiveAbove | 51 | Specifies Perspective Above.
msoCameraPerspectiveAboveLeftFacing | 53 | Specifies Perspective Above Left Facing.
msoCameraPerspectiveAboveRightFacing | 54 | Specifies Perspective Above Right Facing.
msoCameraPerspectiveBelow | 52 | Specifies Perspective Below.
msoCameraPerspectiveContrastingLeftFacing | 55 | Specifies Perspective Contrasting Left Facing.
msoCameraPerspectiveContrastingRightFacing | 56 | Specifies Perspective Contrasting Right Facing.
msoCameraPerspectiveFront | 48 | Specifies Perspective Front.
msoCameraPerspectiveHeroicExtremeLeftFacing | 59 | Specifies Perspective Heroic Extreme Left Facing.
msoCameraPerspectiveHeroicExtremeRightFacing | 60 | Specifies Perspective Heroic Extreme Right Facing.
msoCameraPerspectiveHeroicLeftFacing | 57 | Specifies Perspective Heroic Left Facing.
msoCameraPerspectiveHeroicRightFacing | 58 | Specifies Perspective Heroic Right Facing.
msoCameraPerspectiveLeft | 49 | Specifies Perspective Left.
msoCameraPerspectiveRelaxed | 61 | Specifies Perspective Relaxed.
msoCameraPerspectiveRelaxedModerately | 62 | Specifies Perspective Relaxed Moderately.
msoCameraPerspectiveRight | 50 | Specifies Perspective Right.
msoPresetCameraMixed | -2 | Specifies a mixed effect.


MsoPresetExtrusionDirection Enumeration (Office)

 Copy code hover
[image]

MsoPresetExtrusionDirection Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the direction that the extrusion's sweep path takes away from the extruded shape (the front face of the extrusion). Used with the PresetExtrusionDirection property of the ThreeDFormat object.

Name | Value | Description
msoExtrusionBottom | 2 | Lower part.
msoExtrusionBottomLeft | 3 | Lower left.
msoExtrusionBottomRight | 1 | Lower right.
msoExtrusionLeft | 6 | Left.
msoExtrusionNone | 5 | No extrusion.
msoExtrusionRight | 4 | Right.
msoExtrusionTop | 8 | Upper part.
msoExtrusionTopLeft | 9 | Upper left.
msoExtrusionTopRight | 7 | Upper right.
msoPresetExtrusionDirectionMixed | -2 | Return value only; indicates a combination of the other states.


MsoPresetGradientType Enumeration (Office)

 Copy code hover
[image]

MsoPresetGradientType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies which predefined gradient to use to fill a shape.

Name | Value | Description
msoGradientBrass | 20 | Brass gradient.
msoGradientCalmWater | 8 | Calm Water gradient.
msoGradientChrome | 21 | Chrome gradient.
msoGradientChromeII | 22 | Chrome II gradient.
msoGradientDaybreak | 4 | Daybreak gradient.
msoGradientDesert | 6 | Desert gradient.
msoGradientEarlySunset | 1 | Early Sunset gradient.
msoGradientFire | 9 | Fire gradient.
msoGradientFog | 10 | Fog gradient.
msoGradientGold | 18 | Gold gradient.
msoGradientGoldII | 19 | Gold II gradient.
msoGradientHorizon | 5 | Horizon gradient.
msoGradientLateSunset | 2 | Late Sunset gradient.
msoGradientMahogany | 15 | Mahogany gradient.
msoGradientMoss | 11 | Moss gradient.
msoGradientNightfall | 3 | Nightfall gradient.
msoGradientOcean | 7 | Ocean gradient.
msoGradientParchment | 14 | Parchment gradient.
msoGradientPeacock | 12 | Peacock gradient.
msoGradientRainbow | 16 | Rainbow gradient.
msoGradientRainbowII | 17 | Rainbow II gradient.
msoGradientSapphire | 24 | Sapphire gradient.
msoGradientSilver | 23 | Silver gradient.
msoGradientWheat | 13 | Wheat gradient.
msoPresetGradientMixed | -2 | Mixed gradient.


MsoPresetLightingDirection Enumeration (Office)

 Copy code hover
[image]

MsoPresetLightingDirection Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the location of lighting on an extruded (three-dimensional) shape relative to the shape.

Name | Value | Description
msoLightingBottom | 8 | Lighting comes from the lower part.
msoLightingBottomLeft | 7 | Lighting comes from the lower left.
msoLightingBottomRight | 9 | Lighting comes from the lower right.
msoLightingLeft | 4 | Lighting comes from the left.
msoLightingNone | 5 | No lighting.
msoLightingRight | 6 | Lighting comes from the right.
msoLightingTop | 2 | Lighting comes from the upper part.
msoLightingTopLeft | 1 | Lighting comes from the upper left.
msoLightingTopRight | 3 | Lighting comes from the upper right.
msoPresetLightingDirectionMixed | -2 | Not supported.


MsoPresetLightingSoftness Enumeration (Office)

 Copy code hover
[image]

MsoPresetLightingSoftness Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the intensity of light used on a shape.

Name | Value | Description
msoLightingBright | 3 | Bright light.
msoLightingDim | 1 | Dim light.
msoLightingNormal | 2 | Normal light.
msoPresetLightingSoftnessMixed | -2 | Not supported.


MsoPresetMaterial Enumeration (Office)

 Copy code hover
[image]

MsoPresetMaterial Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the extrusion surface material. Used with the PresetMaterial property of the ThreeDFormat object.

Name | Value | Description
msoMaterialClear | 13 | Clear
msoMaterialDarkEdge | 11 | DarkEdge
msoMaterialFlat | 14 | Flat
msoMaterialMatte | 1 | Matte
msoMaterialMatte2 | 5 | Matte2
msoMaterialMetal | 3 | Metal
msoMaterialMetal2 | 7 | Metal2
msoMaterialPlastic | 2 | Plastic
msoMaterialPlastic2 | 6 | Plastic2
msoMaterialPowder | 10 | Powder
msoMaterialSoftEdge | 12 | Soft Edge
msoMaterialSoftMetal | 15 | Soft Metal
msoMaterialTranslucentPowder | 9 | Translucent Powder
msoMaterialWarmMatte | 8 | Warm Matte
msoMaterialWireFrame | 4 | Wireframe
msoPresetMaterialMixed | -2 | Mixed Material


MsoPresetTextEffect Enumeration (Office)

 Copy code hover
[image]

MsoPresetTextEffect Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies what text effect to use on a WordArt object. Refer to the WordArt Gallery dialog box in any Microsoft Office product that supports WordArt to see a preview of each effect. The values of the MsoPresetTextEffect constants correspond to the formats listed in the WordArt Gallery dialog box (numbered from left to right and from top to bottom).

Name | Value | Description
msoTextEffect1 | 0 | First text effect.
msoTextEffect10 | 9 | Tenth text effect.
msoTextEffect11 | 10 | Eleventh text effect.
msoTextEffect12 | 11 | Twelfth text effect.
msoTextEffect13 | 12 | Thirteenth text effect.
msoTextEffect14 | 13 | Fourteenth text effect.
msoTextEffect15 | 14 | Fifteenth text effect.
msoTextEffect16 | 15 | Sixteenth text effect.
msoTextEffect17 | 16 | Seventeenth text effect.
msoTextEffect18 | 17 | Eighteenth text effect.
msoTextEffect19 | 18 | Nineteenth text effect.
msoTextEffect2 | 1 | Second text effect.
msoTextEffect20 | 19 | Twentieth text effect.
msoTextEffect21 | 20 | Twenty-first text effect.
msoTextEffect22 | 21 | Twenty-second text effect.
msoTextEffect23 | 22 | Twenty-third text effect.
msoTextEffect24 | 23 | Twenty-fourth text effect.
msoTextEffect25 | 24 | Twenty-fifth text effect.
msoTextEffect26 | 25 | Twenty-sixth text effect.
msoTextEffect27 | 26 | Twenty-seventh text effect.
msoTextEffect28 | 27 | Twenty-eighth text effect.
msoTextEffect29 | 28 | Twenty-ninth text effect.
msoTextEffect3 | 2 | Third text effect.
msoTextEffect30 | 29 | Thirtieth text effect.
msoTextEffect31 | 30 | Thirty-first text effect.
msoTextEffect32 | 31 | Thirty-second text effect.
msoTextEffect33 | 32 | Thirty-third text effect.
msoTextEffect34 | 33 | Thirty-fourth text effect.
msoTextEffect35 | 34 | Thirty-fifth text effect.
msoTextEffect36 | 35 | Thirty-sixth text effect.
msoTextEffect37 | 36 | Thirty-seventh text effect.
msoTextEffect38 | 37 | Thirty-eighth text effect.
msoTextEffect39 | 38 | Thirty-ninth text effect.
msoTextEffect4 | 3 | Fourth text effect.
msoTextEffect40 | 39 | Fortieth text effect.
msoTextEffect41 | 40 | Forty-first text effect.
msoTextEffect42 | 41 | Forty-second text effect.
msoTextEffect43 | 42 | Forty-third text effect.
msoTextEffect44 | 43 | Forty-fourth text effect.
msoTextEffect45 | 44 | Forty-fifth text effect.
msoTextEffect46 | 45 | Forty-sixth text effect.
msoTextEffect47 | 46 | Forty-seventh text effect.
msoTextEffect48 | 47 | Forty-eighth text effect.
msoTextEffect49 | 48 | Forty-ninth text effect.
msoTextEffect5 | 4 | Fifth text effect.
msoTextEffect50 | 49 | Fiftieth text effect.
msoTextEffect6 | 5 | Sixth text effect.
msoTextEffect7 | 6 | Seventh text effect.
msoTextEffect8 | 7 | Eighth text effect.
msoTextEffect9 | 8 | Ninth text effect.
msoTextEffectMixed | -2 | Not used.


MsoPresetTextEffectShape Enumeration (Office)

 Copy code hover
[image]

MsoPresetTextEffectShape Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies shape of WordArt text. You can see a preview of each text effect shape by selecting WordArt Shape in the WordArt toolbar.

Name | Value | Description
msoTextEffectShapeArchDownCurve | 10 | Text is an arch that curves down.
msoTextEffectShapeArchDownPour | 14 | Text is a 3-D arch that curves down.
msoTextEffectShapeArchUpCurve | 9 | Text is an arch that curves up.
msoTextEffectShapeArchUpPour | 13 | Text is a 3-D arch that curves up.
msoTextEffectShapeButtonCurve | 12 | Text is curved around a center "button."
msoTextEffectShapeButtonPour | 16 | Text is seen in 3-D, curved around a center "button."
msoTextEffectShapeCanDown | 20 | Text is stretched to fill the height of the shape, with only a slight curve down.
msoTextEffectShapeCanUp | 19 | Text is stretched to fill the height of the shape, with only a slight curve up.
msoTextEffectShapeCascadeDown | 40 | Text slants up and to the right as font size decreases.
msoTextEffectShapeCascadeUp | 39 | Text slants down and to the right as font size increases.
msoTextEffectShapeChevronDown | 6 | Text slants up to its center point and then slants down.
msoTextEffectShapeChevronUp | 5 | Text slants down to its center point and then slants up.
msoTextEffectShapeCircleCurve | 11 | Text follows a circle, reading clockwise.
msoTextEffectShapeCirclePour | 15 | Text has a 3-D effect and follows a circle, reading clockwise.
msoTextEffectShapeCurveDown | 18 | Text curves down and to the right as font size decreases.
msoTextEffectShapeCurveUp | 17 | Text curves down and to the right as font size increases.
msoTextEffectShapeDeflate | 26 | Font size decreases to the text's midpoint, then increases to the starting size.
msoTextEffectShapeDeflateBottom | 28 | Font size decreases to the text's midpoint, then increases to the starting size, while keeping the top of the text along the same curve.
msoTextEffectShapeDeflateInflate | 31 | Font size increases to the text's midpoint, then decreases to the starting size.
msoTextEffectShapeDeflateInflateDeflate | 32 | Font size decreases, increases, and decreases again across the text.
msoTextEffectShapeDeflateTop | 30 | Font size decreases to the text's midpoint, then increases to the starting size, while keeping the bottom of the text along the same curve.
msoTextEffectShapeDoubleWave1 | 23 | Text follows a line that curves up, then down, then up and down again.
msoTextEffectShapeDoubleWave2 | 24 | Text follows a line that curves down, then up, then down and up again.
msoTextEffectShapeFadeDown | 36 | Top of the text appears to be closer to the viewer than bottom of the text.
msoTextEffectShapeFadeLeft | 34 | Left side of text appears to be closer to the viewer than right side.
msoTextEffectShapeFadeRight | 33 | Right side of text appears to be closer to the viewer than left side.
msoTextEffectShapeFadeUp | 35 | Bottom of text appears to be closer to the viewer than top.
msoTextEffectShapeInflate | 25 | Font size of text increases to its center point, then decreases. Center point of each letter is on the same straight line.
msoTextEffectShapeInflateBottom | 27 | Font size of text increases to its center point, then decreases. Center point of each letter follows an arch that curves downward.
msoTextEffectShapeInflateTop | 29 | Font size of text increases to its center point, then decreases. Center point of each letter follows an arch that curves upward.
msoTextEffectShapeMixed | -2 | Not used.
msoTextEffectShapePlainText | 1 | No shape applied.
msoTextEffectShapeRingInside | 7 | Text appears to be written inside a 3-D ring.
msoTextEffectShapeRingOutside | 8 | Text appears to be written outside a 3-D ring.
msoTextEffectShapeSlantDown | 38 | Text slants down and to the right.
msoTextEffectShapeSlantUp | 37 | Text slants up and to the right.
msoTextEffectShapeStop | 2 | Text follows the shape of a stop sign.
msoTextEffectShapeTriangleDown | 4 | Text slants up, then down.
msoTextEffectShapeTriangleUp | 3 | Text slants down, then up.
msoTextEffectShapeWave1 | 21 | Text follows a wave up, then down and up again.
msoTextEffectShapeWave2 | 22 | Text follows a wave down, then up and down again.


MsoPresetTexture Enumeration (Office)

 Copy code hover
[image]

MsoPresetTexture Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies texture to be used to fill a shape.

Name | Value | Description
msoPresetTextureMixed | -2 | Not used.
msoTextureBlueTissuePaper | 17 | Blue tissue paper texture.
msoTextureBouquet | 20 | Bouquet texture.
msoTextureBrownMarble | 11 | Brown marble texture.
msoTextureCanvas | 2 | Canvas texture.
msoTextureCork | 21 | Cork texture.
msoTextureDenim | 3 | Denim texture.
msoTextureFishFossil | 7 | Fish fossil texture.
msoTextureGranite | 12 | Granite texture.
msoTextureGreenMarble | 9 | Green marble texture.
msoTextureMediumWood | 24 | Medium wood texture.
msoTextureNewsprint | 13 | Newsprint texture.
msoTextureOak | 23 | Oak texture.
msoTexturePaperBag | 6 | Paper bag texture.
msoTexturePapyrus | 1 | Papyrus texture.
msoTextureParchment | 15 | Parchment texture.
msoTexturePinkTissuePaper | 18 | Pink tissue paper texture.
msoTexturePurpleMesh | 19 | Purple mesh texture.
msoTextureRecycledPaper | 14 | Recycled paper texture.
msoTextureSand | 8 | Sand texture.
msoTextureStationery | 16 | Stationery texture.
msoTextureWalnut | 22 | Walnut texture.
msoTextureWaterDroplets | 5 | Water droplets texture.
msoTextureWhiteMarble | 10 | White marble texture.
msoTextureWovenMat | 4 | Woven mat texture.


MsoPresetThreeDFormat Enumeration (Office)

 Copy code hover
[image]

MsoPresetThreeDFormat Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies an extrusion (three-dimensional) format.The msoPresetThreeDFormat constants are numbered according to the order (left to right, top to bottom) in which they are shown in the 3-D Style button on the Formatting toolbar.

Name | Value | Description
msoPresetThreeDFormatMixed | -2 | Not used.
msoThreeD1 | 1 | First 3-D format.
msoThreeD10 | 10 | Tenth 3-D format.
msoThreeD11 | 11 | Eleventh 3-D format.
msoThreeD12 | 12 | Twelfth 3-D format.
msoThreeD13 | 13 | Thirteenth 3-D format.
msoThreeD14 | 14 | Fourteenth 3-D format.
msoThreeD15 | 15 | Fifteenth 3-D format.
msoThreeD16 | 16 | Sixteenth 3-D format.
msoThreeD17 | 17 | Seventeenth 3-D format.
msoThreeD18 | 18 | Eighteenth 3-D format.
msoThreeD19 | 19 | Nineteenth 3-D format.
msoThreeD2 | 2 | Second 3-D format.
msoThreeD20 | 20 | Twentieth 3-D format.
msoThreeD3 | 3 | Third 3-D format.
msoThreeD4 | 4 | Fourth 3-D format.
msoThreeD5 | 5 | Fifth 3-D format.
msoThreeD6 | 6 | Sixth 3-D format.
msoThreeD7 | 7 | Seventh 3-D format.
msoThreeD8 | 8 | Eighth 3-D format.
msoThreeD9 | 9 | Ninth 3-D format.


MsoRecolorType Enumeration (Office)

 Copy code hover
[image]

MsoRecolorType Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the type of recolor to use when changing a color scheme.

Name | Value | Description
msoRecolorType1 | 1 | Specifies recolor Type1
msoRecolorType10 | 10 | Specifies recolor Type10
msoRecolorType2 | 2 | Specifies recolor Type2
msoRecolorType3 | 3 | Specifies recolor Type3
msoRecolorType4 | 4 | Specifies recolor Type4
msoRecolorType5 | 5 | Specifies recolor Type5
msoRecolorType6 | 6 | Specifies recolor Type6
msoRecolorType7 | 7 | Specifies recolor Type7
msoRecolorType8 | 8 | Specifies recolor Type8
msoRecolorType9 | 9 | Specifies recolor Type9
msoRecolorTypeMixed | -2 | Specifies a mixture of recolor types.
msoRecolorTypeNone | 0 | Specifies no recolor type.


MsoReflectionType Enumeration (Office)

 Copy code hover
[image]

MsoReflectionType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type of the ReflectionFormat object.

Version Information

Version Added: Office Core 2007

Name | Value | Description
msoReflectionType1 | 1 | Type 1.
msoReflectionType2 | 2 | Type 2.
msoReflectionType3 | 3 | Type 3.
msoReflectionType4 | 4 | Type 4.
msoReflectionType5 | 5 | Type 5.
msoReflectionType6 | 6 | Type 6.
msoReflectionType7 | 7 | Type 7.
msoReflectionType8 | 8 | Type 8.
msoReflectionType9 | 9 | Type 9.
msoReflectionTypeMixed | -2 | Return value only; indicates a combination of the other states.
msoReflectionTypeNone | 0 | No reflection type.


MsoRelativeNodePosition Enumeration (Office)

 Copy code hover
[image]

MsoRelativeNodePosition Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies where a node is added to a diagram relative to existing nodes.

Name | Value | Description
msoAfterLastSibling | 4 | Node is added after last sibling.
msoAfterNode | 2 | Node is added after current node.
msoBeforeFirstSibling | 3 | Node is added before first sibling.
msoBeforeNode | 1 | Node is added before current node.


MsoScaleFrom Enumeration (Office)

 Copy code hover
[image]

MsoScaleFrom Enumeration (Office)
Send feedback

Specifies which part of the shape retains its position when the shape is scaled.

Name | Value | Description
msoScaleFromBottomRight | 2 | Shape's lower right corner retains its position.
msoScaleFromMiddle | 1 | Shape's midpoint retains its position.
msoScaleFromTopLeft | 0 | Shape's upper left corner retains its position.


MsoScreenSize Enumeration (Office)

 Copy code hover
[image]

MsoScreenSize Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the ideal screen resolution to be used to view a document in a Web browser.

Name | Value | Description
msoScreenSize1024x768 | 4 | 1024x768 resolution.
msoScreenSize1152x882 | 5 | 1152x882 resolution.
msoScreenSize1152x900 | 6 | 1152x900 resolution.
msoScreenSize1280x1024 | 7 | 1280x1024 resolution.
msoScreenSize1600x1200 | 8 | 1600x1200 resolution.
msoScreenSize1800x1440 | 9 | 1800x1440 resolution.
msoScreenSize1920x1200 | 10 | 1920x1200 resolution.
msoScreenSize544x376 | 0 | 544x376 resolution.
msoScreenSize640x480 | 1 | 640x480 resolution.
msoScreenSize720x512 | 2 | 720x512 resolution.
msoScreenSize800x600 | 3 | 800x600 resolution.


MsoSearchIn Enumeration (Office)

 Copy code hover
[image]

MsoSearchIn Enumeration (Office)
Send feedback

This object or member is deprecated and is not intended to be used in your code.


MsoSegmentType Enumeration (Office)

 Copy code hover
[image]

MsoSegmentType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type for a segment. Used with the Insert and AddNodes methods of the FreeformBuilder object.

Name | Value | Description
msoSegmentCurve | 1 | Curve.
msoSegmentLine | 0 | Line.


MsoShadowStyle Enumeration (Office)

 Copy code hover
[image]

MsoShadowStyle Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type of shadowing effect.

Name | Value | Description
msoShadowStyleInnerShadow | 1 | Specifies the inner shadow effect.
msoShadowStyleMixed | -2 | Specifies a combination of inner and outer shadow effects.
msoShadowStyleOuterShadow | 2 | Specifies the outer shadow effect.


MsoShadowType Enumeration (Office)

 Copy code hover
[image]

MsoShadowType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type of shadow displayed with a shape.The msoShadowType constants are numbered according to their order (left to right, top to bottom) within the Shadow Style set shown in the Drawing toolbar.

Name | Value | Description
msoShadow1 | 1 | First shadow type.
msoShadow10 | 10 | Tenth shadow type.
msoShadow11 | 11 | Eleventh shadow type.
msoShadow12 | 12 | Twelfth shadow type.
msoShadow13 | 13 | Thirteenth shadow type.
msoShadow14 | 14 | Fourteenth shadow type.
msoShadow15 | 15 | Fifteenth shadow type.
msoShadow16 | 16 | Sixteenth shadow type.
msoShadow17 | 17 | Seventeenth shadow type.
msoShadow18 | 18 | Eighteenth shadow type.
msoShadow19 | 19 | Nineteenth shadow type.
msoShadow2 | 2 | Second shadow type.
msoShadow20 | 20 | Twentieth shadow type.
msoShadow3 | 3 | Third shadow type.
msoShadow4 | 4 | Fourth shadow type.
msoShadow5 | 5 | Fifth shadow type.
msoShadow6 | 6 | Sixth shadow type.
msoShadow7 | 7 | Seventh shadow type.
msoShadow8 | 8 | Eighth shadow type.
msoShadow9 | 9 | Ninth shadow type.
msoShadowMixed | -2 | Not supported.


MsoShapeStyleIndex Enumeration (Office)

 Copy code hover
[image]

MsoShapeStyleIndex Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the line and shape style.

Name | Value | Description
msoLineStyle1 | 10001 | Line Style 1
msoLineStyle10 | 10010 | Line Style 10
msoLineStyle11 | 10011 | Line Style 11
msoLineStyle12 | 10012 | Line Style 12
msoLineStyle13 | 10013 | Line Style 13
msoLineStyle14 | 10014 | Line Style 14
msoLineStyle15 | 10015 | Line Style 15
msoLineStyle16 | 10016 | Line Style 16
msoLineStyle17 | 10017 | Line Style 17
msoLineStyle18 | 10018 | Line Style 18
msoLineStyle19 | 10019 | Line Style 19
msoLineStyle2 | 10002 | Line Style 2
msoLineStyle20 | 10020 | Line Style 20
msoLineStyle3 | 10003 | Line Style 3
msoLineStyle4 | 10004 | Line Style 4
msoLineStyle5 | 10005 | Line Style 5
msoLineStyle6 | 10006 | Line Style 6
msoLineStyle7 | 10007 | Line Style 7
msoLineStyle8 | 10008 | Line Style 8
msoLineStyle9 | 10009 | Line Style 9
msoShapeStyle1 | 1 | Shape Style 1
msoShapeStyle10 | 10 | Shape Style 10
msoShapeStyle11 | 11 | Shape Style 11
msoShapeStyle12 | 12 | Shape Style 12
msoShapeStyle13 | 13 | Shape Style 13
msoShapeStyle14 | 14 | Shape Style 14
msoShapeStyle15 | 15 | Shape Style 15
msoShapeStyle16 | 16 | Shape Style 16
msoShapeStyle17 | 17 | Shape Style 17
msoShapeStyle18 | 18 | Shape Style 18
msoShapeStyle19 | 19 | Shape Style 19
msoShapeStyle2 | 2 | Shape Style 2
msoShapeStyle20 | 20 | Shape Style 20
msoShapeStyle3 | 3 | Shape Style 3
msoShapeStyle4 | 4 | Shape Style 4
msoShapeStyle5 | 5 | Shape Style 5
msoShapeStyle6 | 6 | Shape Style 6
msoShapeStyle7 | 7 | Shape Style 7
msoShapeStyle8 | 8 | Shape Style 8
msoShapeStyle9 | 9 | Shape Style 9
msoShapeStyleMixed | -2 | A mix of shape styles.
msoShapeStyleNone | 0 | No shape style.


MsoShapeType Enumeration (Office)

 Copy code hover
[image]

MsoShapeType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type of a shape or range of shapes.

Name | Value | Description
msoAutoShape | 1 | AutoShape.
msoCallout | 2 | Callout.
msoCanvas | 20 | Canvas.
msoChart | 3 | Chart.
msoComment | 4 | Comment.
msoDiagram | 21 | Diagram.
msoEmbeddedOLEObject | 7 | Embedded OLE object.
msoFormControl | 8 | Form control.
msoFreeform | 5 | Freeform.
msoGroup | 6 | Group.
msoIgxGraphic | 24 | SmartArt graphic
msoInk | 22 | Ink
msoInkComment | 23 | Ink comment
msoLine | 9 | Line
msoLinkedOLEObject | 10 | Linked OLE object
msoLinkedPicture | 11 | Linked picture
msoMedia | 16 | Media
msoOLEControlObject | 12 | OLE control object
msoPicture | 13 | Picture
msoPlaceholder | 14 | Placeholder
msoScriptAnchor | 18 | Script anchor
msoShapeTypeMixed | -2 | Mixed shape type
msoTable | 19 | Table
msoTextBox | 17 | Text box
msoTextEffect | 15 | Text effect
msoWebVideo | 26 | Web video


MsoSharedWorkspaceTaskPriority Enumeration (Office)

 Copy code hover
[image]

MsoSharedWorkspaceTaskPriority Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the priority for a shared workspace task.

Name | Value | Description
msoSharedWorkspaceTaskPriorityHigh | 1 | High priority.
msoSharedWorkspaceTaskPriorityLow | 3 | Low priority.
msoSharedWorkspaceTaskPriorityNormal | 2 | Normal priority.


MsoSharedWorkspaceTaskStatus Enumeration (Office)

 Copy code hover
[image]

MsoSharedWorkspaceTaskStatus Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the status of a shared workspace task.

Name | Value | Description
msoSharedWorkspaceTaskStatusCompleted | 3 | Completed.
msoSharedWorkspaceTaskStatusDeferred | 4 | Deferred.
msoSharedWorkspaceTaskStatusInProgress | 2 | In progress.
msoSharedWorkspaceTaskStatusNotStarted | 1 | Not started.
msoSharedWorkspaceTaskStatusWaiting | 5 | Waiting.


MsoSignatureSubset Enumeration (Office)

 Copy code hover
[image]

MsoSignatureSubset Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies properties of the signature subset. These settings act as filters for signature sets.

Name | Value | Description
msoSignatureSubsetAll | 5 | All non-visible signatures plus all signature lines.
msoSignatureSubsetSignatureLines | 2 | All signature lines.
msoSignatureSubsetSignatureLinesSigned | 3 | Signature lines that have been signed.
msoSignatureSubsetSignatureLinesUnsigned | 4 | Signature lines that have not been signed.
msoSignatureSubsetSignaturesAllSigs | 0 | All non-visible signatures plus all signed signature lines.
msoSignatureSubsetSignaturesNonVisible | 1 | All non-visible signatures.


MsoSmartArtNodePosition Enumeration (Office)

 Copy code hover
[image]

MsoSmartArtNodePosition Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies constants that define the different ways to add a new node to the data model in SmartArt.

Name | Value | Description
msoSmartArtNodeAbove | 4 | Insert a node above the SmartArt node in the data model.
msoSmartArtNodeAfter | 2 | Insert a node after the SmartArt node in the data model. Corresponds to clicking Add Shape After in the SmartArt ribbon.
msoSmartArtNodeBefore | 3 | Insert a node before the SmartArt node in the data model.
msoSmartArtNodeBelow | 5 | Insert a node below the SmartArt node in the data model.
msoSmartArtNodeDefault | 1 | The default. Corresponds to clicking Add Shape in the SmartArt ribbon.


MsoSmartArtNodeType Enumeration (Office)

 Copy code hover
[image]

MsoSmartArtNodeType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies constants that define the types of SmartArt nodes.

Name | Value | Description
msoSmartArtNodeTypeAssistant | 2 | Defines an assistant node, which can be used within hierarchical diagrams.
msoSmartArtNodeTypeDefault | 1 | The default node type.


MsoSoftEdgeType Enumeration (Office)

 Copy code hover
[image]

MsoSoftEdgeType Enumeration (Office)
Send feedback

Published: July 09, 2012

Name | Value | Description
msoSoftEdgeType1 | 1 | Soft Edge Type 1
msoSoftEdgeType2 | 2 | Soft Edge Type 2
msoSoftEdgeType3 | 3 | Soft Edge Type 3
msoSoftEdgeType4 | 4 | Soft Edge Type 4
msoSoftEdgeType5 | 5 | Soft Edge Type 5
msoSoftEdgeType6 | 6 | Soft Edge Type 6
msoSoftEdgeTypeNone | 0 | No soft edge.
SoftEdgeTypeMixed | -2 | A mix of soft edge types.


MsoSyncConflictResolutionType Enumeration (Office)

 Copy code hover
[image]

MsoSyncConflictResolutionType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies how conflicts should be resolved when synchronizing a shared document. Used with the ResolveConflict method of the Sync object.

Name | Value | Description
msoSyncConflictClientWins | 0 | Replace the server copy with the local copy.
msoSyncConflictMerge | 2 | Merge changes made to the server copy into the local copy. To resolve the conflict with the merged changes winning, you must save the active document after merging changes, then call the ResolveConflict method again with the msoSyncConflictClientWins option.
msoSyncConflictServerWins | 1 | Replace the local copy with the server copy.


MsoSyncErrorType Enumeration (Office)

 Copy code hover
[image]

MsoSyncErrorType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies a document synchronization error.

Note Note

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Name | Value | Description
msoSyncErrorCouldNotCompare | 13 | Source and destination files could not be compared.
msoSyncErrorCouldNotConnect | 2 | Could not connect.
msoSyncErrorCouldNotOpen | 11 | Could not open file.
msoSyncErrorCouldNotResolve | 14 | Could not resolve files.
msoSyncErrorCouldNotUpdate | 12 | Could not update destination file.
msoSyncErrorFileInUse | 6 | Destination file in use.
msoSyncErrorFileNotFound | 4 | Destination file not found.
msoSyncErrorFileTooLarge | 5 | File too large to synchronize.
msoSyncErrorNone | 0 | No error.
msoSyncErrorNoNetwork | 15 | No network available.
msoSyncErrorOutOfSpace | 3 | Out of space.
msoSyncErrorUnauthorizedUser | 1 | Unauthorized user.
msoSyncErrorUnknown | 16 | Unknown error.
msoSyncErrorUnknownDownload | 10 | Download error.
msoSyncErrorUnknownUpload | 9 | Upload error.
msoSyncErrorVirusDownload | 8 | Virus downloaded.
msoSyncErrorVirusUpload | 7 | Virus uploaded.


MsoSyncEventType Enumeration (Office)

 Copy code hover
[image]

MsoSyncEventType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the return value of a Sync event. In Microsoft Word, used with the Sync event of the Document object or the DocumentSync event of the Application object. In Microsoft Excel, used with the Sync event of the Workbook object or the WorkbookSync event of the Application object. In Microsoft PowerPoint, used with the PresentationSync event of the Application object.

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Name | Value | Description
msoSyncEventDownloadFailed | 2 | Download failed.
msoSyncEventDownloadInitiated | 0 | Download initiated.
msoSyncEventDownloadNoChange | 6 | No change detected.
msoSyncEventDownloadSucceeded | 1 | Download succeeded.
msoSyncEventOffline | 7 | Offline.
msoSyncEventUploadFailed | 5 | Upload failed.
msoSyncEventUploadInitiated | 3 | Upload initiated.
msoSyncEventUploadSucceeded | 4 | Upload succeeded.


MsoSyncStatusType Enumeration (Office)

 Copy code hover
[image]

MsoSyncStatusType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the status of the synchronization of the local copy of the active document with the server copy. Used with the Status property of the Sync object.

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Name | Value | Description
msoSyncStatusConflict | 4 | Both the local and the server copies have changes.
msoSyncStatusError | 6 | An error occurred. Use ErrorType property of Sync object to determine exact error.
msoSyncStatusLatest | 1 | Documents are already in sync.
msoSyncStatusLocalChanges | 3 | Only local copy has changes.
msoSyncStatusNewerAvailable | 2 | Only server copy has changes.
msoSyncStatusNoSharedWorkspace | 0 | No shared workspace.
msoSyncStatusNotRoaming | 0 | No syncronization is needed.
msoSyncStatusSuspended | 5 | Syncronization has been suspended.


MsoSyncVersionType Enumeration (Office)

 Copy code hover
[image]

MsoSyncVersionType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies which version of a shared document to open alongside the currently open local version.

Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

Name | Value | Description
msoSyncVersionLastViewed | 0 | Opens the copy of the document that is created whenever the user overwrites the local copy with the server copy.
msoSyncVersionServer | 1 | Opens the server version.


MsoTabStopType Enumeration (Office)

 Copy code hover
[image]

MsoTabStopType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the type of tab stop.

Name | Value | Description
msoTabStopCenter | 2 | Center tab stop.
msoTabStopDecimal | 4 | Decimal tab stop.
msoTabStopLeft | 1 | Left tab stop.
msoTabStopMixed | -2 | Return value only; indicates a combination of the other states.
msoTabStopRight | 3 | Right tab stop.


MsoTargetBrowser Enumeration (Office)

 Copy code hover
[image]

MsoTargetBrowser Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies target browser for documents viewed in a Web browser.

Name | Value | Description
msoTargetBrowserIE4 | 2 | Microsoft Internet Explorer 4.0.
msoTargetBrowserIE5 | 3 | Microsoft Internet Explorer 5.
msoTargetBrowserIE6 | 4 | Microsoft Internet Explorer 6.
msoTargetBrowserV3 | 0 | Netscape Navigator 3.
msoTargetBrowserV4 | 1 | Netscape Navigator 4.


MsoTextCaps Enumeration (Office)

 Copy code hover
[image]

MsoTextCaps Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the capitalization of the text.

Name | Value | Description
msoAllCaps | 2 | Display the text as all uppercase letters.
msoCapsMixed | -2 | Display the text as mixed uppercase and lowercase letters.
msoNoCaps | 0 | Display the text with no uppercase letters.
msoSmallCaps | 1 | Display the text as with all lowercasee letters.


MsoTextChangeCase Enumeration (Office)

 Copy code hover
[image]

MsoTextChangeCase Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the capitalization of text.

Name | Value | Description
msoCaseLower | 2 | Display the text as lowercase characters.
msoCaseSentence | 1 | Display the text as sentence case characters. Sentence case specifies that the first letter of the sentence is capitalized and that all others should be lowercase (with some exceptions such as proper nouns, and acronyms).
msoCaseTitle | 4 | Display the text as title case characters. Title case specifies that the first letter of each word is capitalized and that all others should be lowercase. In some cases short articles, prepositions, and conjunctions are not capitalized.
msoCaseToggle | 5 | Indicates that lowercase text should be converted to uppercase and that uppercase text should be converted to lowercase text.
msoCaseUpper | 3 | Display the text as uppercase characters.


MsoTextCharWrap Enumeration (Office)

 Copy code hover
[image]

MsoTextCharWrap Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the type of text wrap.

Name | Value | Description
msoCharWrapMixed | -2 | Specifies a mixed text wrap.
msoCustomCharWrap | 3 | Specifies a custom text wrap scheme.
msoNoCharWrap | 0 | Specifies no text wrapping.
msoStandardCharWrap | 1 | Specifies wrapping text around the standard boundry of an object.
msoStrictCharWrap | 2 | Specifies text wrapping that adheres to restrictions imposed by some languages such as Chinese and Japanese alphabets.


MsoTextDirection Enumeration (Office)

 Copy code hover
[image]

MsoTextDirection Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the direction that text runs.

Name | Value | Description
msoTextDirectionLeftToRight | 1 | Text runs left to right.
msoTextDirectionMixed | -2 | Return value only; indicates a combination of the other states.
msoTextDirectionRightToLeft | 2 | Text runs right to left.


MsoTextEffectAlignment Enumeration (Office)

 Copy code hover
[image]

MsoTextEffectAlignment Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies alignment for WordArt text.

Name | Value | Description
msoTextEffectAlignmentCentered | 2 | Centered.
msoTextEffectAlignmentLeft | 1 | Left-aligned.
msoTextEffectAlignmentLetterJustify | 4 | Text is justified. Spacing between letters may be adjusted to justify text.
msoTextEffectAlignmentMixed | -2 | Not used.
msoTextEffectAlignmentRight | 3 | Right- aligned.
msoTextEffectAlignmentStretchJustify | 6 | Text is justified. Letters may be stretched to justify text.
msoTextEffectAlignmentWordJustify | 5 | Text is justified. Spacing between words (but not letters) may be adjusted to justify text.


MsoTextFontAlign Enumeration (Office)

 Copy code hover
[image]

MsoTextFontAlign Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the text alignment scheme used for an object.

Name | Value | Description
msoFontAlignAuto | 0 | Specifies that the text alignment will be determined by the Office application.
msoFontAlignBaseline | 3 | Specifies that the font is aligned to the baseline of the object.
msoFontAlignBottom | 4 | Specifies that the font is aligned to the bottom of the object.
msoFontAlignCenter | 2 | Specifies that the font is aligned to the center of the object.
msoFontAlignMixed | -2 | Specifies that there is a mix of text alignments used with the object.
msoFontAlignTop | 1 | Specifies that the font is aligned to the top of the object.


MsoTextOrientation Enumeration (Office)

 Copy code hover
[image]

MsoTextOrientation Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies orientation for text.

Name | Value | Description
msoTextOrientationDownward | 3 | Downward.
msoTextOrientationHorizontal | 1 | Horizontal.
msoTextOrientationHorizontalRotatedFarEast | 6 | Horizontal and rotated as required for Asian language support.
msoTextOrientationMixed | -2 | Not supported.
msoTextOrientationUpward | 2 | Upward.
msoTextOrientationVertical | 5 | Vertical.
msoTextOrientationVerticalFarEast | 4 | Vertical as required for Asian language support.


MsoTextStrike Enumeration (Office)

 Copy code hover
[image]

MsoTextStrike Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the number of times a character is printed to darken the image.

Name | Value | Description
msoDoubleStrike | 2 | Specifies that the character is printed twice.
msoNoStrike | 0 | Specifies that the character is not printed.
msoSingleStrike | 1 | Specifies that the character is printed once.
msoStrikeMixed | -2 | Specifies that the text can contain a combination of doublestrike and single strike characters.


MsoTextTabAlign Enumeration (Office)

 Copy code hover
[image]

MsoTextTabAlign Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the text alignment against tab stops or line breaks.

Name | Value | Description
msoTabAlignCenter | 1 | Specifies that the following text up to next tab or line break is centered on the designated tab stop.
msoTabAlignDecimal | 3 | Specifies that the following text is searched for the first occurrence of the character representing the decimal point. The text up to the next tab or line break is then aligned such that the decimal point starts at the designated tab stop.
msoTabAlignLeft | 0 | Specifies that the following text starts immediately after the designated tab stop (the default).
msoTabAlignMixed | -2 | Specifies that mixed text alignment against tab stops is used.
msoTabAlignRight | 2 | Specifies that the following text up to the next tab or line break is rendered flush right to the designated tab stop.


MsoTextUnderlineType Enumeration (Office)

 Copy code hover
[image]

MsoTextUnderlineType Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the type of underline for text.

Name | Value | Description
msoNoUnderline | 0 | Specifies no underline.
msoUnderlineDashHeavyLine | 8 | Specifies a dash underline.
msoUnderlineDashLine | 7 | Specifies a dash line underline.
msoUnderlineDashLongHeavyLine | 10 | Specifies a long heavy line underline.
msoUnderlineDashLongLine | 9 | Specifies a dashed long line underline.
msoUnderlineDotDashHeavyLine | 12 | Specifies a dot dash heavy line underline.
msoUnderlineDotDashLine | 11 | Specifies a dot dash line underline.
msoUnderlineDotDotDashHeavyLine | 14 | Specifies a dot dot dash heavy line underline.
msoUnderlineDotDotDashLine | 13 | Specifies a dot dot dash line underline.
msoUnderlineDottedHeavyLine | 6 | Specifies a dotted heavy line underline.
msoUnderlineDottedLine | 5 | Specifies a dotted line underline.
msoUnderlineDoubleLine | 3 | Specifies a double line underline.
msoUnderlineHeavyLine | 4 | Specifies a heavy line underline.
msoUnderlineMixed | -2 | Specifies a mixed of underline types.
msoUnderlineSingleLine | 2 | Specifies a single line underline.
msoUnderlineWavyDoubleLine | 17 | Specifies a wavy double line underline.
msoUnderlineWavyHeavyLine | 16 | Specifies a wavy heavy line underline.
msoUnderlineWavyLine | 15 | Specifies a wavy line underline.
msoUnderlineWords | 1 | Specifies underlining words.


MsoTextureAlignment Enumeration (Office)

 Copy code hover
[image]

MsoTextureAlignment Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the alignment (the origin of the coordinate grid) for the tiling of the texture fill.

Name | Value | Description
msoTextureAlignmentMixed | -2 | Return value only; indicates a combination of the other states.
msoTextureBottom | 7 | Bottom alignment.
msoTextureBottomLeft | 6 | Bottom-left alignment.
msoTextureBottomRight | 8 | Bottom-right alignment.
msoTextureCenter | 4 | Center alignment.
msoTextureLeft | 3 | Left alignment.
msoTextureRight | 5 | Right alignment.
msoTextureTop | 1 | Top alignment.
msoTextureTopLeft | 0 | Top-left alignment.
msoTextureTopRight | 2 | Top-right alignment.


MsoTextureType Enumeration (Office)

 Copy code hover
[image]

MsoTextureType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the texture type for the selected fill.

Name | Value | Description
msoTexturePreset | 1 | Preset texture type.
msoTextureTypeMixed | -2 | Return value only; indicates a combination of the other states.
msoTextureUserDefined | 2 | User-defined texture type.


MsoThemeColorIndex Enumeration (Office)

 Copy code hover
[image]

MsoThemeColorIndex Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the Office theme color.

Name | Value | Description
msoNotThemeColor | 0 | Specifies no theme color.
msoThemeColorAccent1 | 5 | Specifies the Accent 1 theme color.
msoThemeColorAccent2 | 6 | Specifies the Accent 2 theme color.
msoThemeColorAccent3 | 7 | Specifies the Accent 3 theme color.
msoThemeColorAccent4 | 8 | Specifies the Accent 4 theme color.
msoThemeColorAccent5 | 9 | Specifies the Accent 5 theme color.
msoThemeColorAccent6 | 10 | Specifies the Accent 6 theme color.
msoThemeColorBackground1 | 14 | Specifies the Background 1 theme color.
msoThemeColorBackground2 | 16 | Specifies the Background 2 theme color.
msoThemeColorDark1 | 1 | Specifies the Dark 1 theme color.
msoThemeColorDark2 | 3 | Specifies the Dark 2 theme color.
msoThemeColorFollowedHyperlink | 12 | Specifies the theme color for a clicked hyperlink.
msoThemeColorHyperlink | 11 | Specifies the theme color for a hyperlink.
msoThemeColorLight1 | 2 | Specifies the Light 1 theme color.
msoThemeColorLight2 | 4 | Specifies the Light 2 theme color.
msoThemeColorMixed | -2 | Specifies a mixed color theme.
msoThemeColorText1 | 13 | Specifies the Text 1 theme color.
msoThemeColorText2 | 15 | Specifies the Text 2 theme color.


MsoThemeColorSchemeIndex Enumeration (Office)

 Copy code hover
[image]

MsoThemeColorSchemeIndex Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the color scheme for an Office theme.

Name | Value | Description
msoThemeAccent1 | 5 | Specifies color scheme Accent 1.
msoThemeAccent2 | 6 | Specifies color scheme Accent 2.
msoThemeAccent3 | 7 | Specifies color scheme Accent 3.
msoThemeAccent4 | 8 | Specifies color scheme Accent 4.
msoThemeAccent5 | 9 | Specifies color scheme Accent 5.
msoThemeAccent6 | 10 | Specifies color scheme Accent 6.
msoThemeDark1 | 1 | Specifies color scheme Dark 1.
msoThemeDark2 | 3 | Specifies color scheme Dark 2.
msoThemeFollowedHyperlink | 12 | Specifies a color scheme for a clicked hyperlink.
msoThemeHyperlink | 11 | Specifies a color scheme for a hyperlink.
msoThemeLight1 | 2 | Specifies color scheme Light 1.
msoThemeLight2 | 4 | Specifies color scheme Light 2.


MsoTriState Enumeration (Office)

 Copy code hover
[image]

MsoTriState Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies a tri-state Boolean value.

Name | Value | Description
msoCTrue | 1 | Not supported.
msoFalse | 0 | False.
msoTriStateMixed | -2 | Not supported.
msoTriStateToggle | -3 | Not supported.
msoTrue | -1 | True.


MsoVerticalAnchor Enumeration (Office)

 Copy code hover
[image]

MsoVerticalAnchor Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the vertical alignment of text in a text frame. Used with the VerticalAnchor property of the TextFrame object.

Name | Value | Description
msoAnchorBottom | 4 | Aligns text to bottom of text frame.
msoAnchorBottomBaseLine | 5 | Anchors bottom of text string to current position, regardless of text resizing. When you resize text without baseline anchoring, text centers itself on previous position.
msoAnchorMiddle | 3 | Centers text vertically.
msoAnchorTop | 1 | Aligns text to top of text frame.
msoAnchorTopBaseline | 2 | Anchors bottom of text string to current position, regardless of text resizing. When you resize text without baseline anchoring, text centers itself on previous position.
msoVerticalAnchorMixed | -2 | Return value only; indicates a combination of the other states.


MsoWarpFormat Enumeration (Office)

 Copy code hover
[image]

MsoWarpFormat Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates various image warping formats.

Name | Value | Description
msoWarpFormat1 | 0 | Specifies Warp Format 1.
msoWarpFormat10 | 9 | Specifies Warp Format 10.
msoWarpFormat11 | 10 | Specifies Warp Format 11.
msoWarpFormat12 | 11 | Specifies Warp Format 12.
msoWarpFormat13 | 12 | Specifies Warp Format 13.
msoWarpFormat14 | 13 | Specifies Warp Format 14.
msoWarpFormat15 | 14 | Specifies Warp Format 15.
msoWarpFormat16 | 15 | Specifies Warp Format 16.
msoWarpFormat17 | 16 | Specifies Warp Format 17.
msoWarpFormat18 | 17 | Specifies Warp Format 18.
msoWarpFormat19 | 18 | Specifies Warp Format 19.
msoWarpFormat2 | 1 | Specifies Warp Format 2.
msoWarpFormat20 | 19 | Specifies Warp Format 20.
msoWarpFormat21 | 20 | Specifies Warp Format 21.
msoWarpFormat22 | 21 | Specifies Warp Format 22.
msoWarpFormat23 | 22 | Specifies Warp Format 23.
msoWarpFormat24 | 23 | Specifies Warp Format 24.
msoWarpFormat25 | 24 | Specifies Warp Format 25.
msoWarpFormat26 | 25 | Specifies Warp Format 26.
msoWarpFormat27 | 26 | Specifies Warp Format 27.
msoWarpFormat28 | 27 | Specifies Warp Format 28.
msoWarpFormat29 | 28 | Specifies Warp Format 29.
msoWarpFormat3 | 2 | Specifies Warp Format 3.
msoWarpFormat30 | 29 | Specifies Warp Format 30.
msoWarpFormat31 | 30 | Specifies Warp Format 31.
msoWarpFormat32 | 31 | Specifies Warp Format 32.
msoWarpFormat33 | 32 | Specifies Warp Format 33.
msoWarpFormat34 | 33 | Specifies Warp Format 34.
msoWarpFormat35 | 34 | Specifies Warp Format 35.
msoWarpFormat36 | 35 | Specifies Warp Format 36.
msoWarpFormat37 | 36 | Specifies Warp Format 37.
msoWarpFormat4 | 3 | Specifies Warp Format 4.
msoWarpFormat5 | 4 | Specifies Warp Format 5.
msoWarpFormat6 | 5 | Specifies Warp Format 6.
msoWarpFormat7 | 6 | Specifies Warp Format 7.
msoWarpFormat8 | 7 | Specifies Warp Format 8.
msoWarpFormat9 | 8 | Specifies Warp Format 9.
msoWarpFormatMixed | -2 | Specifies a mix of warp formats.


MsoWizardActType Enumeration (Office)

 Copy code hover
[image]

MsoWizardActType Enumeration (Office)
Send feedback

This object or member is deprecated and is not intended to be used in your code.


MsoWizardMsgType Enumeration (Office)

 Copy code hover
[image]

MsoWizardMsgType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies context under which a wizard's callback procedure is called. Used as an argument in a callback procedure designed for use with a custom wizard.

Name | Value | Description
msoWizardMsgLocalStateOff | 2 | User clicked the right button in the decision or branch balloon.
msoWizardMsgLocalStateOn | 1 | Not supported.
msoWizardMsgResuming | 5 | Passed to the ActivateWizard method if msoWizardActResume is specified for the Act argument.
msoWizardMsgShowHelp | 3 | User clicked the left button in the decision or branch balloon.
msoWizardMsgSuspending | 4 | Passed to the ActivateWizard method if msoWizardActSuspend is specified for the Act argument.


MsoZOrderCmd Enumeration (Office)

 Copy code hover
[image]

MsoZOrderCmd Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies where in the z-order a shape should be moved relative to other shapes.

Name | Value | Description
msoBringForward | 2 | Bring shape forward.
msoBringInFrontOfText | 4 | Bring shape in front of text.
msoBringToFront | 0 | Bring shape to the front.
msoSendBackward | 3 | Send shape backward.
msoSendBehindText | 5 | Send shape behind text.
msoSendToBack | 1 | Send shape to the back.


OutSpaceSlabStyle Enumeration (Office)

 Copy code hover
[image]

OutSpaceSlabStyle Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies constants that define the styles of the slabs on the File tab.

Name | Value | Description
OutSpaceSlabStyleError | 2 | Error style.
OutSpaceSlabStyleNormal | 0 | Normal style.
OutSpaceSlabStyleWarning | 1 | Warning style.


RibbonControlSize Enumeration (Office)

 Copy code hover
[image]

RibbonControlSize Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies constants that define the size of the controls on the ribbon.

Name | Value | Description
RibbonControlSizeLarge | 1 | Large controls.
RibbonControlSizeRegular | 0 | Small controls.


SignatureDetail Enumeration (Office)

 Copy code hover
[image]

SignatureDetail Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates additional information about a signature.

Name | Value | Description
sigdetApplicationName | 1 | Specifies the application name.
sigdetApplicationVersion | 2 | Specifies the application version.
sigdetColorDepth | 8 | Specifies the color depth.
sigdetDelSuggSigner | 16 | Specifies the suggested signer delegate.
sigdetDelSuggSignerEmail | 20 | Specifies the suggested signer's delegate's e-mail.
sigdetDelSuggSignerEmailSet | 21 | Indicates whether an email for a suggested signer delegate has been specified.
sigdetDelSuggSignerLine2 | 18 | Specifies the suggested signer's delegate's signature line.
sigdetDelSuggSignerLine2Set | 19 | Specifies the set of suggested signer's delegate's signature lines.
sigdetDelSuggSignerSet | 17 | Specifies the set of suggested signer's delegates.
sigdetDocPreviewImg | 10 | Specifies the document preview image.
sigdetHashAlgorithm | 14 | Specifies the hash algorithm.
sigdetHorizResolution | 6 | Specifies the horizontal resolution.
sigdetIPCurrentView | 12 | Specifies the IP current view.
sigdetIPFormHash | 11 | Specifies the IP form hash.
sigdetLocalSigningTime | 0 | Specifies the local signing time.
sigdetNumberOfMonitors | 5 | Specifies the number of monitors
sigdetOfficeVersion | 3 | Specifies the Office version.
sigdetShouldShowViewWarning | 15 | Specifies the Should Show View Warning setting.
sigdetSignatureType | 13 | Specifies the signature type.
sigdetSignedData | 9 | Specifies the signed data.
sigdetVertResolution | 7 | Specifies the vertical resolution.
sigdetWindowsVersion | 4 | Specifies the Windows version.


SignatureLineImage Enumeration (Office)

 Copy code hover
[image]

SignatureLineImage Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the signature line image.

Name | Value | Description
siglnimgSignedInvalid | 3 | The SignedInvalid image.
siglnimgSignedValid | 2 | The SignedValid image.
siglnimgSoftwareRequired | 0 | The SoftwareRequired image.
siglnimgUnsigned | 1 | The Unsigned image.


SignatureProviderDetail Enumeration (Office)

 Copy code hover
[image]

SignatureProviderDetail Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies properties of a signature provider.

Name | Value | Description
sigprovdetHashAlgorithm | 1 | Hash algorithm used to hash the data in the file.
sigprovdetUIOnly | 2 | Indicates that the signature provider only uses a custom user interface.
sigprovdetUrl | 0 | The URL of the signature provider.


SignatureType Enumeration (Office)

 Copy code hover
[image]

SignatureType Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies properties of a signature.

Name | Value | Description
sigtypeMax | 3 | Specifies the maximum number of the signature types available in the current version of Office.
sigtypeNonVisible | 1 | A signature that is not visible in the content of the document.
sigtypeSignatureLine | 2 | A signature that is visible in the content of the document.
sigtypeUnknown | 0 | A signature not generated by Office.


XlDataLabelPosition Enumeration (Office)

 Copy code hover
[image]

XlDataLabelPosition Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates the position of data labels relative to the data markers.

Name | Value | Description
xlLabelPositionAbove | 0 | Data label positioned above point.
xlLabelPositionBelow | 1 | Data label positioned below point.
xlLabelPositionBestFit | 5 | Office application controls position of data label.
xlLabelPositionCenter | -4108 | Data label centered on data point or inside bar or pie.
xlLabelPositionCustom | 7 | Data label centered on data point or inside bar or pie.
xlLabelPositionInsideBase | 4 | Data label positioned arbitrarily.
xlLabelPositionInsideEnd | 3 | Data label positioned arbitrarily.
xlLabelPositionLeft | -4131 | Data label positioned at bottom of bar or pie.
xlLabelPositionMixed | 6 | Data label positioned at bottom of bar or pie.
xlLabelPositionOutsideEnd | 2 | Data label positioned at top of bar or pie.
xlLabelPositionRight | -4152 | Data label positioned at top of bar or pie.


XlDisplayUnit Enumeration (Office)

 Copy code hover
[image]

XlDisplayUnit Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates numeric units of measurement.

Name | Value | Description
xlDisplayUnitCustom | -4114 | Specifies custom units.
xlDisplayUnitNone | -4142 | No units are displayed.
xlHundredMillions | -8 | Specifies units of hundreds of millions.
xlHundreds | -2 | Specifies units of hundreds.
xlHundredThousands | -5 | Specifies units of hundreds of thousands.
xlMillionMillions | -10 | Specifies units of mllions of millions.
xlMillions | -6 | Specifies units of millions.
xlTenMillions | -7 | Specifies units of tens of millions.
xlTenThousands | -4 | Specifies units of tens of thousands.
xlThousandMillions | -9 | Specifies units of thousands of millions.
xlThousands | -3 | Specifies units of thousands.


XlPivotFieldOrientation Enumeration (Office)

 Copy code hover
[image]

XlPivotFieldOrientation Enumeration (Office)
Send feedback

Published: July 09, 2012

Specifies the location of the field in a PivotTable report.

Name | Value | Description
xlColumnField | 2 | Specifies the Column field.
xlDataField | 4 | Specifies the Data field.
xlHidden | 0 | Specifies that the field is hidden.
xlPageField | 3 | Specifies the Page field.
xlRowField | 1 | Specifies the Row field.


XlSizeRepresents Enumeration (Office)

 Copy code hover
[image]

XlSizeRepresents Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates what the size measurement is in relation to.

Name | Value | Description
xlSizeIsArea | 1 | The size measure is for the area.
xlSizeIsWidth | 2 | The size measure is for the width.


XlTimeUnit Enumeration (Office)

 Copy code hover
[image]

XlTimeUnit Enumeration (Office)
Send feedback

Published: July 09, 2012

Indicates units of time measurement.

Name | Value | Description
xlDays | 0 | Specifies Day units.
xlMonths | 1 | Specifies Month units.
xlYears | 2 | Specifies Year units.


Welcome to the Visual Basic for Applications language reference for Office 2013

 Copy code hover
[image]

Welcome to the Visual Basic for Applications language reference for Office 2013
Send feedback

Welcome to the Visual Basic for Applications (VBA) language reference for Office 2013. This reference contains conceptual overviews, programming tasks, samples, and references to guide you in developing solutions based on VBA.

Initial publication: July 2012 | Updated: November 2012

The documentation provided in this reference includes the following:

  • Microsoft Forms reference

    Provides information about Userforms and controls, and how to program with them by using Visual Basic.

  • Visual Basic conceptual topics

    Provides information to help you understand Visual Basic programming.

  • Visual Basic definitions

    Provides a glossary of definitions to help you understand concepts presented in this documentation.

  • Visual Basic how-to topics

    Describes useful common procedures (for example, how to use the Object Browser or how to set Visual Basic Environment options).

  • Visual Basic language reference

    Provides documentation about Visual Basic the language: all its methods, properties, statements, functions, operators, and objects.

  • Visual Basic add-in model

    Describes how to customize the Visual Basic editor, and provides documentation for the object model that enables you to extend the environment.

  • Visual Basic user interface Help

    Describes user interface elements of the Visual Basic Editor, such as commands, dialog boxes, windows, and toolbars.

Additional resources

  • Microsoft Office Developer Center

  • Accessibility in Microsoft Products

  • Document Conventions

  • Visual Basic for Applications Language Reference for Office 2010 Copyright Notice

  • Microsoft Online Privacy Notice


Document conventions (Visual Basic for Applications)

 Copy code hover
[image]

Document conventions (Visual Basic for Applications)
Send feedback

Visual Basic documentation uses the following typographic conventions.

Convention | Description
Sub, If, ChDir, Print, True, Debug | Words in bold with initial letter capitalized indicate language-specific keywords.
Setup | Words you are instructed to type appear in bold.
object, varname, arglist | Italic, lowercase letters indicate placeholders for information you supply.
pathname , filenumber | Bold, italic, and lowercase letters indicate placeholders for arguments where you can use either positional or named-argument syntax.
[expressionlist] | In syntax, items inside brackets are optional.
{While | Until} | In syntax, braces and a vertical bar indicate a mandatory choice between two or more items. You must choose one of the items unless all of the items are also enclosed in brackets. For example: [{This | OrThat}]
ESC, ENTER | Words in capital letters indicate key names and key sequences.
ALT+F1, CTRL+R | A plus sign (+) between key names indicates a combination of keys. For example, ALT+F1 means hold down the ALT key while pressing the F1 key.

Code Conventions

The following code conventions are used:

Sample Code | Description
 | This font is used for code, variables, and error message text.
 | An apostrophe (') introduces code comments.
 | A space and an underscore ( _) continue a line of code.


Microsoft Forms Visual Basic reference

 Copy code hover
[image]

Microsoft Forms Visual Basic reference
Send feedback

In this section

  • Concepts (Microsoft Forms)

  • Glossary (Microsoft Forms)

  • Reference (Microsoft Forms)


Concepts (Microsoft Forms)

 Copy code hover
[image]

Concepts (Microsoft Forms)
Send feedback

In this section

  • Active controls and selected controls

  • Add a control to a form

  • Add a control to the Toolbox

  • Add a customized control to the Toolbox

  • Add items to a list using the List or Column property

  • Adjust horizontal and vertical spacing between controls

  • Align controls

  • Align text in a control

  • Arrange buttons

  • Assign a bitmap to a control

  • Assign a caption

  • Assign a control tip to a control

  • Assign a control tip to a Page or Tab

  • Assign a custom Help topic to a control

  • Assign an accelerator key

  • Assign an accelerator key for a Page or Tab

  • Break up a control group

  • ByVal References in Microsoft Forms

  • Center controls in a form

  • Change the location of the form

  • Change the name of a Toolbox page

  • Change the order of pages in a MultiPage or TabStrip

  • Change the order of Toolbox pages

  • Change the size of the form

  • Change the size of the Toolbox

  • Create a control group

  • Create a list box with option buttons or check boxes

  • Create a new Toolbox page

  • Create a standard list box

  • Create a transparent control

  • Create an option group using the GroupName property

  • Creating Forms and Dialog Boxes with Right-to-Left Extensions

  • Custom Help files

  • Customize a Toolbox icon

  • Customize a ToolTip in the Toolbox

  • Delete a bitmap from a control

  • Delete a Toolbox page

  • Delete an item from the Toolbox

  • Display a group's shortcut menu

  • Display or hide the Toolbox

  • Display the shortcut menu for a MultiPage or Page

  • Display the shortcut menu for a TabStrip or Tab

  • Import or export a Toolbox page

  • ListBox styles

  • Make a control that automatically adjusts to the size of its data

  • Make controls the same size

  • Move an item to another Toolbox page

  • Object model for Microsoft Forms

  • Select a control within a group

  • Select a grid size

  • Set the tab order using the Tab Order dialog box

  • Set the tab order using the TabIndex property

  • Set the ToolTip for a Toolbox page

  • Should I use a MultiPage or a TabStrip?

  • Show or hide the grid

  • Show or hide ToolTips

  • Size all the controls in a group

  • Size to fit

  • Size to grid

  • Things you can do with a multicolumn ListBox or ComboBox

  • Things you can do with a picture on an Image control

  • Things you can do with control groups

  • Tips on selecting multiple controls

  • Tips on setting the dominant control

  • Tips on using text boxes

  • Transparency in Microsoft Forms

  • Undo and Redo in Microsoft Forms

  • Use z-order to layer controls

  • Ways to align a picture on a control

  • Ways to change the appearance of a control

  • Ways to create an option group

  • Ways to match entries in a list

  • Ways to protect sensitive information

  • Ways to put data in a ListBox or ComboBox

  • What is a caption?

  • What is a control tip?

  • What is a MultiPage?

  • What is a shortcut menu?

  • What is a TabStrip?

  • What is a ToolTip?

  • What is the difference between the DataObject and the Clipboard?

  • What is the Toolbox?


Active controls and selected controls

 Copy code hover
[image]

Active controls and selected controls
Send feedback

All controls have an active state and a selected state. When a control is active, it means you are working with the contents of the control; when a control is selected, it means you are working with the control itself.

Most controls are automatically selected when you put them on the form. In design mode, sizing handles appear around a control's border when the control is selected. If you deselect the control, you can select it again by clicking once on the control.

Clicking a control that is selected puts the control in the active state. In this state, you can directly edit the control's caption.

In both the selected state and the active state, you can use DEL, CTRL+X, and CTRL+C as shortcut keys for the Delete, Cut, and Copy commands respectively. In the selected state, these commands are available on the shortcut menu and will affect the control itself. In the active state, these commands will affect whatever text is selected inside the control; if no text is selected, these commands have no effect. These commands are not available on the shortcut menu for active controls.


Add a control to a form

 Copy code hover
[image]

Add a control to a form
Send feedback

Use any of the following methods to add a control from the Toolbox to your form. You can also use these methods to insert a control in a Frame, TabStrip, or MultiPage on the form.

  • Click a control in the Toolbox and then click in the form. The control appears in its default size. You can then drag the control to change its size.

  • Drag a control from the Toolbox to the form. The control appears in its default size.

  • Double-click the control in the Toolbox, and then click in the form once for each control you want to create. For example, to create four command buttons, double-click the CommandButton in the Toolbox and then click four times in the form.


Add a control to the Toolbox

 Copy code hover
[image]

Add a control to the Toolbox
Send feedback

  1. Right-click any control icon in the Toolbox, or an empty area on any page of the Toolbox.

  2. From the shortcut menu, select Additional Controls.

  3. From the Available Controls list, select the new controls.

  4. Click OK.


Add a customized control to the Toolbox

 Copy code hover
[image]

Add a customized control to the Toolbox
Send feedback

  1. Place a control on your form and customize it.

  2. For example, to create an OK button, place a CommandButton on the form, set its Caption property to OK and set its Default property to True.

  3. Select the customized control.

  4. Drag the control to the Toolbox.

Note Note

When you drag a control onto the Toolbox, you only transfer property values. Any code you have written for that control does not transfer with the control. You must write new code for the icon or copy code from the control on the form to the control on the Toolbox.


Add items to a list using the List or Column property

 Copy code hover
[image]

Add items to a list using the List or Column property
Send feedback

  1. Create a multicolumn ListBox or ComboBox.

  2. Create a two-dimensional array that contains the items you want to put in the list.

  3. Set the ColumnCount property of the ListBox or ComboBox to match the number of entries in the list.

  4. Do one of the following:

    • Assign the array as the value of the List property. The contents of the ListBox will match the contents of the array exactly.

    • Assign the array as the value of the Column property. Column transposes rows and columns, so each row of the ListBox matches the corresponding column of the array.


Adjust horizontal and vertical spacing between controls

 Copy code hover
[image]

Adjust horizontal and vertical spacing between controls
Send feedback

  1. Select the controls where you want to adjust spacing.

  2. From the Format menu, choose Horizontal Spacing or Vertical Spacing.

  3. From the cascading menu, choose one of the following:

    • Make Equal — to make all horizontal and vertical spaces between controls the same size. The amount of horizontal and vertical space will vary depending on the area available for displaying controls and the combined width of all controls.

    • Increase — to increase the space between controls by one grid block.

    • Decrease — to decrease the space between controls by one grid block.

    • Remove — to remove the space between controls. The controls do not overlap, but are immediately adjacent to each other.


Align controls

 Copy code hover
[image]

Align controls
Send feedback

  1. Select the controls to align.

  2. Select the dominant control.

  3. From the Format menu, choose Align.

  4. From the cascading menu, choose one of the following to align the specified part of each selected control with the same part of the dominant control:

    • Lefts — to align the left edge.

    • Centers — to align the center of each control. This means a vertical line drawn at the center of the dominant control would contain the center of every selected control.

    • Rights — to align the right edge.

    • Tops — to align the top.

    • Middles — to align the center of each control. This means a horizontal line drawn at the center of the dominant control would also contain the center of every selected control.

    • Bottoms — to align the bottom.

    • To Grid — to align the upper left corner of each selected control with its nearest grid point. Note that this option is not based on the position of the dominant control.

Note Note

Each command on the menu has a small picture that shows how the controls will be aligned.


Align text in a control

 Copy code hover
[image]

Align text in a control
Send feedback

  1. In the Properties window, choose the TextAlign property.

  2. Click the drop-down arrow next to the property's value to display a list of available choices.

  3. Choose one of the following:

    • Left — to align the text with the left edge of the control.

    • Right — to align the text with the right edge of the control.

    • Center — to center the text relative to the length of the control.

TextAlign is available for a ComboBox, Label, and TextBox.


Arrange buttons

 Copy code hover
[image]

Arrange buttons
Send feedback

  1. Select the CommandButton controls to arrange.

  2. From the Format menu, choose Arrange Buttons.

  3. From the cascading menu, choose one of the following:

    • Bottom — to put the buttons in a row starting at the bottom left corner of the form and align the bottoms of all buttons.

    • Right — to put the buttons in a column starting at the upper right corner of the form and align the right edges of all buttons.

After you arrange the buttons, use either Horizontal Spacing or Vertical Spacing on the Format menu to adjust the spacing between the buttons.

Tip Tip

Select a small grid size before choosing this command to position the buttons close to the bottom or right of the form. Changing the grid size after the buttons are in place will not change their position.


Assign a bitmap to a control

 Copy code hover
[image]

Assign a bitmap to a control
Send feedback

In the Properties window:

  1. Choose the Picture property.

  2. In the Picture dialog box, enter the name of the picture and its location.

If the picture is larger than the control, Microsoft Forms scales the picture to fit the control, regardless of whether you assign the picture through the Properties window or through code. The PictureAlignment property determines how it is aligned within the control.


Assign a caption

 Copy code hover
[image]

Assign a caption
Send feedback

To assign a caption to a CheckBox, CommandButton, Frame, Label, OptionButton, or ToggleButton:

  1. Display the control's Properties window.

  2. Select the Caption property.

  3. Enter the text you want to use as the caption.

To assign a caption to a Page or Tab:

  1. Select the MultiPage or TabStrip that contains the Page or Tab.

  2. Select the individual Page or Tab. When the Page or Tab is selected, a rectangle appears around its caption.

  3. Right-click the selected MultiPage or TabStrip.

  4. From the shortcut menu, choose Rename.

  5. In the Caption field, enter the text you want to use as the caption.

  6. Click OK.


Assign a control tip to a control

 Copy code hover
[image]

Assign a control tip to a control
Send feedback

  1. Select the control.

  2. In the Properties window, select the ControlTipText property. You can also set the value of ControlTipText through code.

  3. Enter the string you want to use as the control tip.

Tip Tip

To assign a control tip for a Page or Tab, use the Rename command on the shortcut menu of the Page or Tab.


Assign a control tip to a Page or Tab

 Copy code hover
[image]

Assign a control tip to a Page or Tab
Send feedback

  1. Select an individual Page or Tab. Be sure to select an individual Page or Tab, not the corresponding MultiPage or TabStrip. When a Page or Tab is selected, a rectangle appears around its caption.

  2. Right-click the selected Page or Tab.

  3. From the shortcut menu, choose Rename.

  4. In the ControlTipText field, type the string you want to use as the control tip.

  5. Click OK.

Tip Tip

To assign a control tip for a MultiPage or TabStrip, use the ControlTipText property.


Assign a custom Help topic to a control

 Copy code hover
[image]

Assign a custom Help topic to a control
Send feedback

This procedure assumes you have created a custom Help file and associated it with your project. The procedure for associating a Help file with a project depends on your project environment.

  1. Select a control for which you have written a custom Help topic.

  2. In the Properties window, select the HelpContextID property.

  3. Enter the context ID of the appropriate topic from your custom Help file.


Assign an accelerator key

 Copy code hover
[image]

Assign an accelerator key
Send feedback

  1. In design mode, select the control on the form.

  2. In the Properties window, select the Accelerator property.

  3. Enter a single character as the value for Accelerator.

Tip Tip

Use a character from the caption of the control. Note that the selected character is underlined in the control's caption.


Assign an accelerator key for a Page or Tab

 Copy code hover
[image]

Assign an accelerator key for a Page or Tab
Send feedback

  1. In design mode, select an individual Page or Tab. Be sure to select the Page or Tab, not the associated MultiPage or TabStrip. When a Page or Tab is selected, a rectangle appears around the caption of the Page or Tab.

  2. Right-click the selected Page or Tab.

  3. From the shortcut menu, choose Rename.

  4. In the Rename dialog box, enter a single character in the Accelerator Key field.

Tip Tip

Use a character from the caption of the control. Note that the selected character is underlined in the control's caption.


Break up a control group

 Copy code hover
[image]

Break up a control group
Send feedback

  1. Select the group.

  2. From the Format menu, choose Ungroup.


ByVal References in Microsoft Forms

 Copy code hover
[image]

ByVal References in Microsoft Forms
Send feedback

The ByVal keyword in Microsoft Forms indicates that an argument is passed as a value; this is the standard meaning of ByVal in Visual Basic. However, in Microsoft Forms, you can use ByVal with a ReturnBoolean, ReturnEffect, ReturnInteger, or ReturnString object. When you do, the value passed is not a simple data type; it is a pointer to the object.

When used with these objects, ByVal refers to the object, not the method of passing parameters. Each of the objects listed above has a Value property that you can set. You can also pass that value into and out of a function. Because you can change the values of the object's members, events produce results consistent with ByRef behavior, even though the event syntax says the parameter is ByVal.

Assigning a value to an argument associated with a ReturnBoolean, ReturnEffect, ReturnInteger, or ReturnString is no different from setting the value of any other argument. For example, if the event syntax indicates a Cancel argument used with the ReturnBoolean object, the statement is still valid, just as it is with other data types.


Center controls in a form

 Copy code hover
[image]

Center controls in a form
Send feedback

  1. Select the controls or groups to center.

  2. From the Format menu, choose Center in Form.

  3. From the cascading menu, choose one of the following:

    • Horizontally

    • Vertically


Change the location of the form

 Copy code hover
[image]

Change the location of the form
Send feedback

Through the user interface:

  • Drag the title bar until the form is where you want it.

At design time:

  • Set the form's Left and Top properties to the appropriate values. You can set these properties through the Properties window or through code.


Change the name of a Toolbox page

 Copy code hover
[image]

Change the name of a Toolbox page
Send feedback

  1. Right-click the tab of the Toolbox page whose name you want to change.

  2. From the shortcut menu, choose Rename.

  3. In the Caption field, enter the name you want to use.

  4. Click OK.


Change the order of pages in a MultiPage or TabStrip

 Copy code hover
[image]

Change the order of pages in a MultiPage or TabStrip
Send feedback

  1. Select any page in the MultiPage or TabStrip.

  2. Right-click the caption of the page.

  3. From the shortcut menu, choose Move.

  4. In the Move dialog box, select the Page you want to move.

  5. Choose Move Up or Move Down to change the position of the page.

  6. When you've made all changes you want to, click OK.

Note Note

You can also use the Index property to change the page order through the Properties window. The index of the first page is 0; the index of the second page is 1, and so on.


Change the order of Toolbox pages

 Copy code hover
[image]

Change the order of Toolbox pages
Send feedback

  1. Right-click the tab of any Toolbox page.

  2. From the shortcut menu, choose Move.

  3. Select the name of a page you want to move.

  4. Choose Move Up or Move Down until the page is at the appropriate position in the page list.

  5. Click OK.


Change the size of the form

 Copy code hover
[image]

Change the size of the form
Send feedback

At design time:

  • Drag the sizing handle of the form until the form is the size you want.

At run time:

  • Set the form's Height and Width properties to the appropriate values.


Change the size of the Toolbox

 Copy code hover
[image]

Change the size of the Toolbox
Send feedback

  1. Move the mouse pointer over an edge or a corner of the Toolbox. The pointer changes to a double-ended arrow.

  2. Drag the Toolbox to change its size.


Create a control group

 Copy code hover
[image]

Create a control group
Send feedback

  1. In the form, select each control you want to include in the group.

  2. From the Format menu, choose Group.


Create a list box with option buttons or check boxes

 Copy code hover
[image]

Create a list box with option buttons or check boxes
Send feedback

  1. In the Properties window, select the ListStyle property.

  2. Click the drop-down arrow to display a list of available styles.

  3. From the list, choose Option.

When the ListStyle property is set to Option, the MultiSelect property determines whether check boxes or option buttons appear in the list. When MultiSelect is Single, option buttons appear in the list. When MultiSelect is Multi or Extended, check boxes appear in the list.


Create a new Toolbox page

 Copy code hover
[image]

Create a new Toolbox page
Send feedback

  1. Right-click the tab of any Toolbox page. The new page will be inserted after this page.

  2. Choose New Page.


Create a standard list box

 Copy code hover
[image]

Create a standard list box
Send feedback

  1. In the Properties window, select the ListStyle property.

  2. Click the drop-down arrow to display a list of available styles.

  3. From the list, choose Plain.


Create a transparent control

 Copy code hover
[image]

Create a transparent control
Send feedback

  1. Put the basic control onto the form.

  2. View the control's properties.

  3. Set the BackStyle property to Transparent.

  4. If the control supports the BorderStyle property, set it to None.

Note Note

When you make a control transparent, the background color does not display, so the BackColor property is ignored. However, the setting for BackColor is not changed when a control is transparent.


Create an option group using the GroupName property

 Copy code hover
[image]

Create an option group using the GroupName property
Send feedback

  1. Place all required OptionButton controls on the form. Note that option buttons in a MultiPage or Frame will automatically form an option group.

  2. Identify the buttons for each group you want to create.

  3. Enter a value for the Name property of each control.

  4. For each button in a group, set the GroupName property to the same value.


Creating Forms and Dialog Boxes with Right-to-Left Extensions

 Copy code hover
[image]

Creating Forms and Dialog Boxes with Right-to-Left Extensions
Send feedback

You can use the Visual Basic Editor and Microsoft Forms version 2.0 in all Microsoft Office 2000 applications to create forms and dialog boxes. Bidirectional extensions to the editor and Microsoft Forms 2.0 are provided in Office 2000 for right-to-left, left-to-right, and mixed-text usage. For a general overview of the standard tools, see the "Forms" topic in Help for the application you're working in.

Three Microsoft Forms 2.0 properties are generally used to add bidirectional characteristics to forms and dialog boxes. These properties are listed and described in the following table.

Property | Exposed on | Affects
Alignment | Controls | Controls
TextAlign | Controls | Controls
RightToLeft | Forms | Forms and controls

These properties affect the controls listed in the following table, which are available in the Control Toolbox. You can set these properties in the Properties window in the editor or by using Visual Basic for Applications statements.

Control | Alignment | TextAlign | RightToLeft
CheckBox | X | X | X
ComboBox |  | X | X
Frame |  |  | X
Label |  | X |
ListBox |  | X | X
MultiPage |  |  | X
OptionButton | X | X |
TabStrip |  |  | X
TextBox |  | X | X
ToggleButton |  | X |
Note Note

Context reading order is generally assigned to text in controls. This means that the reading order of displayed text strings that begin with a non-left-to-right character (for example, text strings in Arabic) will be displayed in right-to-left reading order, and text strings that begin with a left-to-right character will be displayed in left-to-right reading order.


Custom Help files

 Copy code hover
[image]

Custom Help files
Send feedback

As an application developer, you can use a custom Help file to provide information about how to use your form application.

To create a custom Help file, use a product or tool that creates Windows Help files.

You can associate a specific topic in your custom Help file with each control in your application. When your application is running, the user can view your Help topic by selecting the control and pressing F1.


Customize a Toolbox icon

 Copy code hover
[image]

Customize a Toolbox icon
Send feedback

  1. Right-click the icon in the Toolbox.

  2. From the shortcut menu, choose Customize.

  3. Do one of the following:

    • To change the ToolTip, enter the new text for the ToolTip.

    • To edit the icon, choose Edit Picture. Then choose the color you want to use and choose the pixel in the image where you want to apply that color.

    • To assign a new bitmap, choose Load Picture. Then identify the file that contains the bitmap you want to use as the icon. If you attempt to load a picture that is larger than an icon, an error occurs.


Customize a ToolTip in the Toolbox

 Copy code hover
[image]

Customize a ToolTip in the Toolbox
Send feedback

  1. Select the control in the Toolbox.

  2. Right-click.

  3. From the shortcut menu, choose Customize. The Customize command will include the name of the control, such as "Customize Label."

  4. Enter the new text for the ToolTip.

  5. Click OK.


Delete a bitmap from a control

 Copy code hover
[image]

Delete a bitmap from a control
Send feedback

In the Properties window:

  1. Highlight the value of the Picture property (the word "bitmap").

  2. Press DELETE.

Or, in code:

  • Enter the following statement: Object.Picture = LoadPicture("")


Delete a Toolbox page

 Copy code hover
[image]

Delete a Toolbox page
Send feedback

  1. Right-click the tab of the Toolbox page you want to delete.

  2. Choose Delete Page. All controls on the page are deleted at the same time.


Delete an item from the Toolbox

 Copy code hover
[image]

Delete an item from the Toolbox
Send feedback

  1. In the Toolbox, right-click the icon of the item you want to remove.

  2. Click Delete on the shortcut menu.

Note Note

If you are deleting controls, you can use Additional Controls from the shortcut menu, and clear the check boxes of all controls you want to delete.


Display a group's shortcut menu

 Copy code hover
[image]

Display a group's shortcut menu
Send feedback

  1. Select the group.

  2. Right-click anywhere inside the rectangle that surrounds the group.

Tip Tip

Click anywhere in the group, but not on the shortcut menu, to make the shortcut menu go away if you don't want to use any of the commands on the menu.


Display or hide the Toolbox

 Copy code hover
[image]

Display or hide the Toolbox
Send feedback

On the View menu, determine whether a check mark appears in front of Toolbox. If the check mark is present, the Toolbox is displayed. If not, the Toolbox is hidden.

Do one of the following:

  • To display the Toolbox, make sure a check mark appears in front of Toolbox. If not, select Toolbox.

  • To hide the Toolbox, make sure there is no check mark in front of Toolbox. If there is, select Toolbox to remove it.


Display the shortcut menu for a MultiPage or Page

 Copy code hover
[image]

Display the shortcut menu for a MultiPage or Page
Send feedback

  1. Make sure the form isn't running.

  2. Do one of the following:

    • To display the shortcut menu of an individual Page, right-click the caption of the appropriate page.

    • To display the shortcut menu of the entire MultiPage, right-click anywhere in the control, but not on the caption of any Page in the control.


Display the shortcut menu for a TabStrip or Tab

 Copy code hover
[image]

Display the shortcut menu for a TabStrip or Tab
Send feedback

  1. Make sure the form isn't running.

  2. Do one of the following:

    • To display the shortcut menu of an individual Tab, select the appropriate tab.

    • When the tab is selected, a dotted rectangle appears around its caption. Right-click the selected caption.

    • To display the shortcut menu of the TabStrip, right-click anywhere in the control, but not on the caption of any Tab in the control.


Import or export a Toolbox page

 Copy code hover
[image]

Import or export a Toolbox page
Send feedback

  1. Right-click the tab of any page in the Toolbox. If you import a page, it will be inserted after this page.

  2. Do one of the following:

    • To import a page, choose Import Page. Then select the name of the page file you want to import.

    • To export a page, choose Export Page. Then enter a name for the file that will store a copy of the Toolbox page. Exporting a page does not remove it from the Toolbox.

  3. Click OK.


ListBox styles

 Copy code hover
[image]

ListBox styles
Send feedback

You can choose between two presentation styles for a ListBox. Each style provides different ways for users to select items in the list.

If the style is Plain, each item is on a separate row; the user selects an item by highlighting one or more rows.

If the style is Option, an option button or check box appears at the beginning of each row. With this style, the user selects an item by clicking the option button or check box. Check boxes appear only when the MultiSelect property is True.


Make a control that automatically adjusts to the size of its data

 Copy code hover
[image]

Make a control that automatically adjusts to the size of its data
Send feedback

In the Properties window, set the AutoSize property to True.


Make controls the same size

 Copy code hover
[image]

Make controls the same size
Send feedback

  1. Select all the controls you want to be the same size.

  2. Select the dominant control.

  3. From the Format menu, choose Make Same Size.

  4. From the cascading menu, choose one of the following:

    • Width — to make all selected controls the same width as the dominant control.

    • Height — to make all selected controls the same height as the dominant control.

    • Both — to make all selected controls the same height and width as the dominant control.


Move an item to another Toolbox page

 Copy code hover
[image]

Move an item to another Toolbox page
Send feedback

  1. Select a control on any page of the Toolbox.

  2. Drag the control to the tab of the new page. Hold the mouse pointer over the tab until the page appears at the front of the Toolbox.

  3. Drag the control onto the main region of the page.

Note Note

If the page you want to place the control on is not visible, you can increase the width of the Toolbox to display tabs for all the pages, and then drag the control to the appropriate page.


Object model for Microsoft Forms

 Copy code hover
[image]

Object model for Microsoft Forms
Send feedback

The Microsoft Forms object model includes the following types of object:

  • Controls

  • Collections

  • Objects (within collections)

Each element of the Microsoft Forms object model has some combination of properties, events, and methods that you can use to make your application work the way you want it to.

Microsoft Forms has three collections:

Controls collection — contains all the controls on a form, Frame, or Page.

Pages collection — contains all the Page objects in a MultiPage. Each MultiPage has its own distinct Pages collection.

Tabs collection — contains all the Tab objects in a TabStrip. Each TabStrip has its own distinct Tabs collection.


Select a control within a group

 Copy code hover
[image]

Select a control within a group
Send feedback

  1. Select the group.

  2. Select a single control within the group. The sizing handles around the group become lighter, and dark handles appear on the selected control. You can change the value of the selected control's properties. Any changes you make will affect only the selected control.

  3. When you're finished working with the selected control, click anywhere inside the group, but not on the selected control. The group is still selected. You can select another control in the group or go on to any other task you need to perform.


Select a grid size

 Copy code hover
[image]

Select a grid size
Send feedback

  1. From the Tools menu, choose Options.

  2. In the Options dialog box, choose the General page.

  3. In the Form Grid Settings group, specify the size you want for each grid block. Specifying smaller numbers results in smaller grid blocks.

Tip Tip

If you use the Arrange Buttons command to position command buttons in your application, try a small grid setting. This will allow you to position the buttons closer to the edge of the form.


Set the tab order using the Tab Order dialog box

 Copy code hover
[image]

Set the tab order using the Tab Order dialog box
Send feedback

  1. Make sure no controls are selected.

  2. Right-click in the form, but not on a control.

  3. From the shortcut menu, choose Tab Order.

  4. Select the name of a control you want to reposition in the tab order.

  5. Choose Move Up or Move Down until the control name is in the appropriate position in the tab order.


Set the tab order using the TabIndex property

 Copy code hover
[image]

Set the tab order using the TabIndex property
Send feedback

  1. Identify the tab order you want to use for the form.

    The tab index of the first control in the tab order is 0; the tab index of the second is 1, and so on.

  2. Select a control in the tab order.

  3. In the Properties window, select the TabIndex property.

  4. Enter the appropriate number to identify the control's position in the tab order.


Set the ToolTip for a Toolbox page

 Copy code hover
[image]

Set the ToolTip for a Toolbox page
Send feedback

  1. Select the page of the Toolbox.

  2. Right-click.

  3. From the shortcut menu, choose Rename.

  4. Enter the new text for the ToolTip.

  5. Click OK.


Should I use a MultiPage or a TabStrip?

 Copy code hover
[image]

Should I use a MultiPage or a TabStrip?
Send feedback

If you use a single layout for data, use a TabStrip and map each set of data to its own Tab. If you need several layouts for data, use a MultiPage and assign each layout to its own Page.

Unlike a Page of a MultiPage, the client region of a TabStrip is not a separate form, but a portion of the form that contains the TabStrip. The border of a TabStrip defines a region of the form that you can associate with the tabs. When you place a control in the client region of a TabStrip, you are adding a control to the form that contains the TabStrip.


Show or hide the grid

 Copy code hover
[image]

Show or hide the grid
Send feedback

  1. From the Tools menu, choose Options.

  2. Select the General tab sheet.

  3. Do one of the following:

    • To show the grid, check the Show Grid box.

    • To hide the grid, clear the Show Grid box.

  4. Click OK.


Show or hide ToolTips

 Copy code hover
[image]

Show or hide ToolTips
Send feedback

  1. From the Tools menu, choose Options.

  2. Select the General tab sheet.

  3. Do one of the following:

    • To display ToolTips, check the Show ToolTips box.

    • To hide ToolTips, clear the Show ToolTips box.


Size all the controls in a group

 Copy code hover
[image]

Size all the controls in a group
Send feedback

  1. Select the group. A rectangle with sizing handles surrounds the group to indicate it is selected.

  2. Click one of the sizing handles and drag it to change the size of the rectangle.

  3. Release the mouse button. The size of each control will be changed proportionately to the way you changed the rectangle around the group.


Size to fit

 Copy code hover
[image]

Size to fit
Send feedback

  1. Select the control.

  2. From the Format menu, choose Size to Fit. Microsoft Forms sets the size of the control so it is just large enough to display its picture and any text assigned to the Caption or Text property.


Size to grid

 Copy code hover
[image]

Size to grid
Send feedback

  1. Select the control.

  2. From the Format menu, choose Size to Grid. Microsoft Forms adjusts the size of the selected control so that each corner aligns with a grid point.


Things you can do with a multicolumn ListBox or ComboBox

 Copy code hover
[image]

Things you can do with a multicolumn ListBox or ComboBox
Send feedback

To control the column widths of a multicolumn ListBox or ComboBox, you can specify the width, in points, for all the columns in the ColumnWidths property. Specifying zero for a specific column hides that column of information from the display.

If you want to hide all but one column of a ListBox or ComboBox from the user, you can set the ColumnWidths of the other columns to zero and identify the column of information to display by leaving its ColumnWidths property set to the default value and using the TextColumn property. When the user selects a row, the Text property of the control is set to the value of the column identified by the TextColumn property. In a combo box, the system displays the column designated by the TextColumn property in the text box portion of the control.

Similarly, you can control which column of values is used for the control when the user makes a selection by specifying the column number in the BoundColumn property.


Things you can do with a picture on an Image control

 Copy code hover
[image]

Things you can do with a picture on an Image control
Send feedback

An Image control is not a picture itself; rather, it contains a picture that is stored in a separate file. You cannot edit the picture with the properties of the Image, but you can use them to specify the way the picture appears on the Image.

An interesting application of Image is that you can use it as a background picture for your application. To do this, make the Image the same size as the form. Then, you can place other controls on top of the background.


Things you can do with control groups

 Copy code hover
[image]

Things you can do with control groups
Send feedback

A group is two or more controls on a form that you treat as a single unit. You can include any control on the form in a group. Once controls belong to a group, you can work with the entire group, or you can select a single object.

Microsoft Forms provides many ways to work with groups and the controls in a group. After you select a group, you can do any of the following:

  • Size all controls in the group at the same time. For more information, see Size all the controls in a group.

  • Break up the group so each control is independent of the others. For more information, see Break up a control group.

  • Display the group's shortcut menu, which provides quick access to commands that affect the group. For more information, see Display a group's shortcut menu.

  • Select a single control within the group without breaking up the group, which lets you change property settings of that control without affecting any other control in the group. For more information, see Select a control within a group.


Tips on selecting multiple controls

 Copy code hover
[image]

Tips on selecting multiple controls
Send feedback

You can select more than one control in three ways:

  • SHIFT+CLICK: Microsoft Forms creates an invisible selection rectangle around the selected controls and puts sizing handles on all controls within that rectangle.

  • CTRL+CLICK: Sizing handles only appear on the selected controls, not on controls within the surrounding rectangle. Occasionally, this method may select additional controls that are near to or adjacent to the selected controls. In that case, use the Select Objects pointer explained below.

  • Select Objects pointer on the Toolbox: draw a rectangle over the controls you want to select. All controls that fall within or just touch the rectangle will be selected.

When you select multiple controls, one of the selected controls becomes a reference for the rest of the selected controls and is called the dominant control.


Tips on setting the dominant control

 Copy code hover
[image]

Tips on setting the dominant control
Send feedback

You can set the dominant control in one of the following ways when selecting multiple controls:

  • SHIFT+CLICK: The dominant control is the first control you select using SHIFT+CLICK.

  • CTRL+CLICK: The dominant control is the last control you select using CTRL+CLICK.

  • Select Objects pointer on the Toolbox: The dominant control is nearest the mouse pointer when you begin drawing the rectangle over the controls you want to select.

If you CTRL+CLICK twice on a selected control, that control becomes the dominant control.


Tips on using text boxes

 Copy code hover
[image]

Tips on using text boxes
Send feedback

The TextBox is a flexible control governed by the following properties: Text, MultiLine, WordWrap, and AutoSize.

Text contains the text that's displayed in the text box.

MultiLine controls whether the TextBox can display text as a single line or as multiple lines. Newline characters identify where one line ends and another begins. If MultiLine is False, then the text is truncated instead of wrapped.

WordWrap allows the TextBox to wrap lines of text that are longer than the width of the TextBox into shorter lines that fit.

If you do not use WordWrap, the TextBox starts a new line of text when it encounters a newline character in the text. If WordWrap is turned off, you can have text lines that do not fit completely in the TextBox. The TextBox displays the portions of text that fit inside its width and truncates the portions of text that do not fit. WordWrap is not applicable unless MultiLine is True.

AutoSize controls whether the TextBox adjusts to display all of the text. When using AutoSize with a TextBox, the width of the TextBox shrinks or expands according to the amount of text in the TextBox and the font size used to display the text.

AutoSize works well in the following situations:

  • Displaying a caption of one or more lines.

  • Displaying the contents of a single-line TextBox.

  • Displaying the contents of a multiline TextBox that is read-only to the user.

Note Note

Avoid using AutoSize with an empty TextBox that also uses the MultiLine and WordWrap properties. When the user enters text into a TextBox with these properties, the TextBox automatically sizes to a long narrow box one character wide and as long as the line of text.


Transparency in Microsoft Forms

 Copy code hover
[image]

Transparency in Microsoft Forms
Send feedback

Microsoft Forms supports transparency in two areas: the background of certain controls, and in bitmaps used on certain controls.

The BackStyle property determines whether a control is transparent. A transparent control lets you see what is behind it on the form. This is useful if you have a decorative background on the form and you want to minimize the amount of that background that is hidden behind the controls. For more information on making a control transparent, see Create a transparent control.

You can display a bitmap on many controls in Microsoft Forms. Certain controls support transparent bitmaps, that is, bitmaps in which one or more background color is transparent. Bitmap transparency is not controlled by any control property; it is controlled by the color of the lower-left pixel in the image. Microsoft Forms does not provide a way to edit a bitmap and make it transparent; you must use a picture editor for this purpose.

In Microsoft Forms, bitmaps are always transparent on the following controls:

  • CheckBox

  • CommandButton

  • Label

  • OptionButton

  • ToggleButton

Transparent pictures sometimes have a hazy appearance. If you do not like this appearance, display the picture on a control that supports opaque images.

If you use a transparent bitmap on a control that does not support transparent bitmaps, the bitmap will display correctly but you won't be able to see what's behind it. In Microsoft Forms, the following controls do not support transparent bitmaps:

  • The form window (UserForm)

  • Frame

  • Image

  • MultiPage


Undo and Redo in Microsoft Forms

 Copy code hover
[image]

Undo and Redo in Microsoft Forms
Send feedback

Microsoft Forms supports multiple levels of Undo and Redo commands. This means you can undo a series of actions, not just a single action.

CTRL+Z is the shortcut key for Undo; CTRL+Y is the shortcut key for Redo.

You cannot undo or redo layering commands, such as Send To Back or Bring To Front. For example, if you select an object and click Move Backward on the shortcut menu, you will not be able to undo or redo that action.


Use z-order to layer controls

 Copy code hover
[image]

Use z-order to layer controls
Send feedback

To place a control at the front or back of the z-order:

  1. Select the controls you want to reposition.

  2. From the Format menu, choose Order.

  3. From the cascading menu, select Bring to Front or Send to Back.

To adjust a control one position in the z-order:

  1. Select the controls you want to reposition.

  2. From the Format menu, choose Order.

  3. From the cascading menu, select Bring Forward or Send Backward.

Note Note

You can't Undo or Redo layering commands, such as Send to Back or Bring to Front. For example, if you select an object and click Send Backward on the shortcut menu, you won't be able to Undo or Redo that action.

The Bring to Front, Bring Forward, Send to Back, and Send Backward menu choices let you change the z-order of a control relative to other controls. If the form includes any ListBox, Frame, or MultiPage controls, those controls automatically move as close as possible to the top of the stack. For example, applying Send Backward to a ListBox, Frame, or MultiPage moves the control below other ListBox, Frame, or MultiPage controls, but will not move it below any other type of control in the stack. Similarly, applying Bring Forward to a control other than a ListBox, Frame, or MultiPage will move the control closer to to top of the stack, but will not move it above any ListBox, Frame, or MultiPage in the stack.

Visually, this means that if a ListBox, Frame, or MultiPage and any other Microsoft Forms control are in the same location on a form, the ListBox, Frame, or MultiPage will always appear on top of the other control. If a ListBox, Frame, or MultiPage is in the same place as another ListBox, Frame, or MultiPage, the z-order of the controls determines which control appears on top of the other.


Ways to align a picture on a control

 Copy code hover
[image]

Ways to align a picture on a control
Send feedback

The Picture property assigns a bitmap or other picture to a control. After you assign the picture to the control, you can do any of the following to align the picture on the control:

  • Use the PictureAlignment property to center the picture within the Image or align any corner of the picture with the corresponding corner of the Image.

  • Use the PictureSizeMode property to clip, stretch, or zoom the picture within the Image. Stretching can distort the picture, but zooming will not.

  • Use the PictureTiling property to display multiple copies of the picture within the Image.


Ways to change the appearance of a control

 Copy code hover
[image]

Ways to change the appearance of a control
Send feedback

Microsoft Forms includes several properties that let you define the appearance of controls in your application:

  • ForeColor

  • BackColor, BackStyle

  • BorderColor, BorderStyle

  • SpecialEffect

ForeColor determines the foreground color. The foreground color applies to any text associated with the control, such as the caption or the control's contents.

BackColor and BackStyle apply to the control's background. The background is the area within the control's boundaries, such as the area surrounding the text in a control, but not the control's border. BackColor determines the background color. BackStyle determines whether the background is transparent. A transparent control background is useful if your application design includes a picture as the main background and you want to see that picture through the control.

BorderColor, BorderStyle, and SpecialEffect apply to the control's border. You can use BorderStyle or SpecialEffect to choose a type of border. Only one of these two properties can be used at a time. When you assign a value to one of these properties, the system sets the other property to None. SpecialEffect lets you choose one of several border styles, but only lets you use system colors for the border. BorderStyle supports only one border style, but lets you choose any color that is a valid setting for BorderColor. BorderColor specifies the color of the control's border, and is only valid when you use BorderStyle to create the border.


Ways to create an option group

 Copy code hover
[image]

Ways to create an option group
Send feedback

By default, all OptionButton controls on a container (such as a form, a MultiPage, or a Frame) are part of a single option group. This means that selecting one of the buttons automatically sets all other option buttons on the form to False.

If you want more than one option group on the form, there are two ways to create additional groups:

  • Use the GroupName property to identify related buttons.

  • Put related buttons in a Frame on the form.

The first method is recommended over the second because it reduces the number of controls required in the application. This reduces the disk space required for your application and can improve the performance of your application as well.

Note Note

A TabStrip is not a container. Option buttons in the TabStrip are included in the form's option group. You can use GroupName to create an option group from buttons in a TabStrip.


Ways to match entries in a list

 Copy code hover
[image]

Ways to match entries in a list
Send feedback

Microsoft Forms provides three ways to match a value entered by the user with an entry that exists in the list of a ListBox or ComboBox:

  • No matching — provides no assistance in matching a user's typed entry to an entry in the list.

  • First letter — compares the most recently-typed letter to the first letter of each entry in the list. The first match in the list is selected.

  • Complete — compares the user's entry and tries to find an exact match in an entry from the list.

The matching feature resets after two seconds (six seconds if you are using East Asia settings). For example, if you have a list of the 50 states and you type "CO" quickly, you will find "Colorado." But if you type "CO" slowly, you will find "Ohio" because the auto-complete search resets between letters.

If you choose Complete matching, it is a good idea to sort the list entries alphabetically (you can use the TextColumn property to do this). If the list is not sorted alphabetically, matching may not work correctly. For example, if the list includes Alabama, Louisiana, and Alaska in that order, then "Alabama" will be considered a complete match if the user types "ala." In fact, this result is ambiguous because there are two entries in the list that could match what the user entered. Sorting alphabetically eliminates this ambiguity.


Ways to protect sensitive information

 Copy code hover
[image]

Ways to protect sensitive information
Send feedback

Many applications use data that should be available only to certain users. Here are some suggestions you can use to protect sensitive information in Microsoft Forms:

  • Write code that makes a control (and its data) invisible to unauthorized users. The Visible property makes a control visible or invisible. For more information about Visible, see Visible Property.

  • Write code that sets the control's foreground and background to the same color when unauthorized users run the application. This hides the information from unauthorized users. The ForeColor and BackColor properties determine the foreground color and the background color. For information about ForeColor, see ForeColor Property. For information about BackColor, see BackColor Property.

  • Disable the control when unauthorized users run the application. The Enabled property determines when a control is disabled. For information about Enabled, see Enabled Property.

  • Require a password for access to the application or a specific control. You can use placeholders as the user types each character. The PasswordChar property defines placeholder characters. For information about PasswordChar, see PasswordChar Property.

Note Note

Using passwords or any other techniques listed can improve the security of your application, but does not guarantee the prevention of unauthorized access to your data.


Ways to put data in a ListBox or ComboBox

 Copy code hover
[image]

Ways to put data in a ListBox or ComboBox
Send feedback

In a ListBox or ComboBox with a single column, the AddItem method provides an effective technique for adding an individual entry to the list. In a multicolumn ListBox or ComboBox, however, the List and Column properties offer another technique; you can load the list from a two-dimensional array.


What is a caption?

 Copy code hover
[image]

What is a caption?
Send feedback

A caption is descriptive text that appears directly on or around a control. The following controls can have captions: CheckBox, CommandButton, Frame, Label, OptionButton, and ToggleButton. The Page and Tab objects that are part of the MultiPage and TabStrip also can have captions.


What is a control tip?

 Copy code hover
[image]

What is a control tip?
Send feedback

A control tip is a brief phrase that describes a control, a Page, or a Tab. The control tip appears when the user briefly holds the mouse pointer over a control without clicking. A control tip is very similar to a ToolTip. The difference is that Microsoft Forms provides ToolTips to developers at design time, and developers provide control tips to end-users at run time.

If you assign a control tip to a MultiPage or a TabStrip, control tips for the individual Page or Tab objects within the MultiPage or TabStrip are not displayed.


What is a MultiPage?

 Copy code hover
[image]

What is a MultiPage?
Send feedback

A MultiPage is a control that contains a collection of one or more pages.

Each Page of a MultiPage is a form that contains its own controls, and as such, can have a unique layout. Typically, the pages in a MultiPage have tabs so the user can select the individual pages.

By default, a MultiPage includes two pages, called Page1 and Page2. Each of these is a Page object, and together they represent the Pages collection of the MultiPage. If you add more pages, they become part of the same Pages collection.


What is a shortcut menu?

 Copy code hover
[image]

What is a shortcut menu?
Send feedback

A shortcut menu is a menu that appears when you right-click an object. In Microsoft Forms, the following objects have shortcut menus:

  • The Toolbox, each page in the Toolbox, and each item on a page of the Toolbox.

  • Individual controls on a form.

  • Groups of controls (groups created with the Group command).

  • Containers (such as UserForm).

  • Individual Page objects in a MultiPage.

  • Individual Tab objects in a TabStrip.

  • Multiple controls that aren't in a group.

The commands on a shortcut menu vary depending on the object you select. For example, if you select multiple controls that aren't in a group, the shortcut menu will include the Group command; the shortcut menu for the Toolbox will not.

To display the shortcut menu for a control or container, right-click the object.

For more information on displaying the shortcut menu for a MultiPage or a Page, see Display the shortcut menu for a MultiPage or Page.

For more information on displaying the shortcut menu for a TabStrip or a Tab, see Display the shortcut menu for a TabStrip or Tab.


What is a TabStrip?

 Copy code hover
[image]

What is a TabStrip?
Send feedback

A TabStrip is a control that contains a collection of one or more tabs.

Each Tab of a TabStrip is a separate object that users can select. Visually, a TabStrip also includes a client area that all the tabs in the TabStrip share.

By default, a TabStrip includes two pages, called Tab1 and Tab2. Each of these is a Tab object, and together they represent the Tabs collection of the TabStrip. If you add more pages, they become part of the same Tabs collection.


What is a ToolTip?

 Copy code hover
[image]

What is a ToolTip?
Send feedback

A ToolTip is a short description, usually just a few words, that appears when the user holds the mouse pointer briefly over a control or another part of the user interface without clicking. You can customize ToolTips for controls and for the Toolbox.

The default value for a new control that is copied from a form to the Toolbox is "New" followed by the control type. For example, the default ToolTip for a customized CommandButton (such as OK) is "New CommandButton". If a control has no associated ToolTip, "Unknown" is the default value.

Note Note

The ToolTip is information provided by Microsoft Forms to forms developers in design mode. Each control has a property, ControlTipText, that allows forms developers to give a "ToolTip" to end users while the application is running.


What is the difference between the DataObject and the Clipboard?

 Copy code hover
[image]

What is the difference between the DataObject and the Clipboard?
Send feedback

The DataObject and the Clipboard both provide a means to move data from one place to another. As an application developer, there are several important points to remember when you use either a DataObject or the Clipboard:

  • You can store more than one piece of data at a time on either a DataObject or the Clipboard as long as each piece of data has a different data format. If you store data with a format that is already in use, the new data is saved and the old data is discarded.

  • The Clipboard supports picture formats and text formats. A DataObject currently supports only text formats.

  • A DataObject exists only while your application is running; the Clipboard exists as long as the operating system is running. This means you can put data on the Clipboard and close an application without losing the data. The same is not true with the DataObject. If you close the application that put data on a DataObject, you lose the data.

  • A DataObject is a standard OLE object, while the Clipboard is not. This means the Clipboard can support standard move operations (copy, cut, and paste) but not drag-and-drop operations. You must use the DataObject if you want your application to support drag-and-drop operations.

Tip Tip

You can define your own data format names when you use the SetText method to move data to the Clipboard or a DataObject. This can help distinguish between text that your application moves and text that the user moves.


What is the Toolbox?

 Copy code hover
[image]

What is the Toolbox?
Send feedback

The Toolbox identifies the different controls that you can add to a form, Frame, or Page.

You can customize the Toolbox in many ways including the following:

  • Add pages to the Toolbox.

  • Move controls from one page to another.

  • Rename pages.

  • Add other controls, including ActiveX controls, to the Toolbox.

  • Copy customized controls from the form into the Toolbox.

  • For example, OK and Cancel buttons are special cases of a CommandButton. If you add OK and Cancel templates to the Toolbox, you can quickly add them to other forms.


Glossary (Microsoft Forms)

 Copy code hover
[image]

Glossary (Microsoft Forms)
Send feedback

In this section

  • Glossary (VBA)


Glossary (VBA)

 Copy code hover
[image]

Glossary (VBA)
Send feedback

accelerator key

A single character used as a shortcut for selecting an object. Pressing the ALT key, followed by the accelerator key gives focus to the object and initiates one or more events associated with the object. The specific event or events initiated varies from one object to another. If code is associated with an event, it is processed when the event is initiated. Also called keyboard accelerator, shortcut key, keyboard shortcut.

background color

The color of the client region of an empty window or display screen, on which all drawing and color display takes place.

bound

Describes a control whose contents are associated with a particular data source, such as a cell or cell range in a worksheet.

clear

To change a setting to "off" or remove a value.

client region

The portion of a window where an application displays output such as text or graphics.

context ID

A unique number or string that corresponds to a specific object in an application. Context IDs are used to create links between the application and corresponding Help topics.

control group

A set of controls that are conceptually or logically related. Controls that are conceptually related are usually viewed together but do not necessarily affect each other. Controls that are logically related affect each other. For example, setting one button in a group of option buttons sets the value of all other buttons in the group to False.

control tip

A brief phrase that describes a control, a Page, or a Tab. The control tip appears when the user briefly holds the mouse pointer over a control without clicking. A control tip is similar to a ToolTip. Microsoft Forms provides ToolTips to developers at design time, while developers provide control tips to end-users at run time.

cursor

A piece of software that returns rows of data to the application. A cursor on a result set indicates the current position in the result set.

cycle

To move through a group of objects in a defined order.

data format

The structure or appearance of a unit of data, such as a file, a database record, a cell in a spreadsheet, or text in a word-processing document.

data source

The location of data to which a control is bound, for example, a cell in a worksheet. The current value of the data source can be stored in the Value property of a control. However, the control does not store the data; it only displays the information that is stored in the data source.

dominant control

A reference for the Align command and Make Same Size command on the Format menu. When aligning controls, the selected controls align to the dominant control. When sizing controls, the selected controls are assigned the dimensions of the dominant control.

The dominant control is indicated by white sizing handles. The sizing handles of the other selected controls are black.

drop source

The selected text or object that is dragged in a drag-and-drop operation.

enumerated constant

You can find additional information for an enumerated data item in the description of the property, method, or event that uses the enumeration.

foreground color

The color that is currently selected for drawing or displaying text on screen. In monochrome displays, the foreground color is the color of a bitmap or other graphic.

grid block

The space between two adjacent grid points.

Input Method Editor (IME)

An application that translates what you type into characters of a DBCS language, such as Japanese or Chinese. As the user types, the IME displays possible equivalents. The user selects the most appropriate entry.

inherited property

A property that has acquired the characteristics of another class.

keyboard state

A return value that identifies which keys are pressed and whether the keyboard modifiers SHIFT, CTRL, and ALT are pressed.

OLE container control

A Visual Basic control that is used to link and embed objects from other applications in a Visual Basic application.

OLE status code

The error number portion of a data structure that returns information for error conditions. The data structure is defined by Object Linking and Embedding.

placeholder

A character that masks or hides another character for security reasons. For example, when a user types a password, an asterisk is displayed on the screen to take the place of each character typed.

property page

A grouping of properties presented as a tabbed page of a property sheet.

RGB

A color value system used to describe colors as a mixture of red (R), green (G), and blue (B). The color is defined as a set of three integers (R,G,B) where each integer ranges from 0-255. A value of 0 indicates a total absence of a color component. A value of 255 indicates the highest intensity of a color component.

system colors

Colors that are defined by the operating system for a specific type of monitor and video adapter. In Windows, each color is associated with a specific part of the user interface, such as a window title or a menu.

target

An object onto which the user drops the object being dragged.

transparent

Describes the background of the object if the background is not visible. Instead of the background, you see whatever is behind the object, for example, an image or picture used as a backdrop in your application. Use the BackStyle property to make the background transparent.

unbound

Describes a control that is not related to a worksheet cell. In contrast, a bound control is a data source for a worksheet cell that provides access to display and edit the value of a control.


Reference (Microsoft Forms)

 Copy code hover
[image]

Reference (Microsoft Forms)
Send feedback

In this section

  • Collections (Microsoft Forms)

  • Dialog Boxes (Microsoft Forms)

  • Events (Microsoft Forms)

  • Examples (Microsoft Forms)

  • Methods (Microsoft Forms)

  • Objects (Microsoft Forms)

  • Properties (Microsoft Forms)


Collections (Microsoft Forms)

 Copy code hover
[image]

Collections (Microsoft Forms)
Send feedback

In this section

  • Controls Collection (Microsoft Forms)

  • Pages Collection (Microsoft Forms)

  • Tabs Collection (Microsoft Forms)


Controls Collection (Microsoft Forms)

 Copy code hover
[image]

Controls Collection (Microsoft Forms)
Send feedback

Includes all the controls contained in an object.

Remarks

Each control in the Controls collection of an object has a unique index whose value can be either an integer or a string. The index value for the first control in a collection is 0; the value for the second control is 1, and so on. This value indicates the order in which controls were added to the collection.

If the index is a string, it represents the name of the control. The Name property of a control also specifies a control's name.

You can use the Controls collection to enumerate or count individual controls, and to set their properties. For example, you can enumerate the Controls collection of a particular form and set the Height property of each control to a specified value.

Note Note

The For Each...Next statement is useful for enumerating a collection.


Pages Collection (Microsoft Forms)

 Copy code hover
[image]

Pages Collection (Microsoft Forms)
Send feedback

A Pages collection includes all the pages of a MultiPage.

Remarks

Each Pages collection provides the features to manage the number of pages in the collection and to identify the page that is currently in use.

A Page object has a unique name and index value within a Pages collection. You can reference a Page either by its name or its index value. The index of the first Page in a collection is 0; the index of the second Page is 1; and so on. The default name for the first page is Page1; the default name for the second page is Page2.

The default value of a Pages collection identifies the current Page of a collection.


Tabs Collection (Microsoft Forms)

 Copy code hover
[image]

Tabs Collection (Microsoft Forms)
Send feedback

A Tabs collection includes all Tabs of a TabStrip.

Remarks

Each Tabs collection provides the features to manage the number of tabs in the collection and to identify the tab that is currently in use.

The default value of the Tabs collection identifies the current Tab of a collection.

A Tab object has a unique name and index value within a Tabs collection. You can reference a Tab either by its name or its index value. The index value reflects the ordinal position of the Tab within the collection. The index of the first Tab in a collection is 0; the index of the second Tab is 1; and so on.


Dialog Boxes (Microsoft Forms)

 Copy code hover
[image]

Dialog Boxes (Microsoft Forms)
Send feedback

Published: June 15, 2012

In this section

  • The Additional Controls dialog box (Microsoft Forms)

  • The Customize Control dialog box (Microsoft Forms)

  • The Page Order/Tab Order dialog box (Microsoft Forms)

  • The Rename dialog box (Microsoft Forms)


The Additional Controls dialog box (Microsoft Forms)

 Copy code hover
[image]

The Additional Controls dialog box (Microsoft Forms)
Send feedback

  1. In the Available Controls list, select the control or controls you want to add to the Toolbox.

  2. Click OK.

Tip Tip

You can filter the Available Controls list by selecting options in the Show group.


The Customize Control dialog box (Microsoft Forms)

 Copy code hover
[image]

The Customize Control dialog box (Microsoft Forms)
Send feedback

Contains the ControlTipText property and the icon that represents this control in the Toolbox. With this dialog box, you can define or change the ControlTipText associated with this control, as well as change the icon that is displayed in the Toolbox.

To define or edit ControlTipText:

  • Enter a new value for ControlTipText.

To edit the icon:

  1. Choose the Edit Picture CommandButton.

  2. Use the Image Editor to alter the icon as needed.

To load another icon:

  1. Choose the Load Picture CommandButton.

  2. From the common dialog box, select a picture file.

  3. Click OK to apply the new values.


The Page Order/Tab Order dialog box (Microsoft Forms)

 Copy code hover
[image]

The Page Order/Tab Order dialog box (Microsoft Forms)
Send feedback

To change the position of a page or tab:

  1. Select the name of the Page or Tab you want to move.

  2. Choose Move Up or Move Down until the selected item is in the desired location.

  3. When all items are in the order you want, click OK.


The Rename dialog box (Microsoft Forms)

 Copy code hover
[image]

The Rename dialog box (Microsoft Forms)
Send feedback

Contains the Accelerator, Caption, and ControlTipText property settings for the individual page or tab that has the focus. Contains the Caption and ToolTipText property settings for the current Toolbox page. You can update the values for these properties.

The accelerator key is a keyboard key that the user presses simultaneously with ALT to set the focus to a Page or Tab. The caption is the text in the tab area of a Page or Tab, or the current Toolbox page. The ControlTipText is a brief description of a control that appears when the user holds the mouse pointer over the control without clicking. The ToolTipText is a brief description of a control that appears when the user holds the mouse pointer over the current Toolbox page without clicking.

To set an accelerator for the Page or Tab:

  • Enter a single character for Accelerator.

To rename the Page or Tab:

  • Enter a new value for Caption.

To define ControlTipText for the Page or Tab:

  • Enter a new value for ControlTipText.

To define ToolTipText for the current Toolbox page:

  • Enter a new value for ToolTipText.

Note Note

Click OK to apply the new values to the page, tab, or Toolbox page.


Events (Microsoft Forms)

 Copy code hover
[image]

Events (Microsoft Forms)
Send feedback

In this section

  • AddControl Event

  • AfterUpdate Event

  • BeforeDragOver Event

  • BeforeDropOrPaste Event

  • BeforeUpdate Event

  • Change Event

  • Click Event

  • DblClick Event

  • DropButtonClick Event

  • Enter, Exit Events

  • Error Event

  • KeyDown, KeyUp Events

  • KeyPress Event

  • Layout Event

  • MouseDown, MouseUp Events

  • MouseMove Event

  • RemoveControl Event

  • Scroll Event

  • SpinDown, SpinUp Events

  • Zoom Event


AddControl Event

 Copy code hover
[image]

AddControl Event
Send feedback

Occurs when a control is inserted onto a form, a Frame, or a Page of a MultiPage.

Syntax

For Frame
Private Sub object_AddControl( )

For MultiPage
Private Sub object_AddControl( index As Long, ctrl As Control)

The AddControl event syntax has these parts:

Part | Description
object | Required. A valid object.
index | Required. The index of the Page that will contain the new control.
ctrl | Required. The control to be added.

Remarks

The AddControl event occurs when a control is added at run time. This event is not initiated when you add a control at design time, nor is it initiated when a form is initially loaded and displayed at run time.

The default action of this event is to add a control to the specified form, Frame, or MultiPage.

The Add method initiates the AddControl event.


AfterUpdate Event

 Copy code hover
[image]

AfterUpdate Event
Send feedback

Occurs after data in a control is changed through the user interface.

Syntax

Private Sub object_AfterUpdate( )

The AfterUpdate event syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

The AfterUpdate event occurs regardless of whether the control is bound (that is, when the RowSource property specifies a data source for the control). This event cannot be canceled. If you want to cancel the update (to restore the previous value of the control), use the BeforeUpdate event and set the Cancel argument to True.

The AfterUpdate event occurs after the BeforeUpdate event and before the Exit event for the current control and before the Enter event for the next control in the tab order.


BeforeDragOver Event

 Copy code hover
[image]

BeforeDragOver Event
Send feedback

Occurs when a drag-and-drop operation is in progress.

Syntax

For Frame
Private Sub object_BeforeDragOver( ByVal Cancel As MSForms.ReturnBoolean, ctrl As Control, ByVal Data As DataObject, ByVal X As Single, ByVal Y As Single, ByVal DragState As fmDragState, ByVal Effect As MSForms.ReturnEffect, ByVal Shift As fmShiftState)

For MultiPage
Private Sub object_BeforeDragOver( index As Long, ByVal Cancel As MSForms.ReturnBoolean, ctrl As Control, ByVal Data As DataObject, ByVal X As Single, ByVal Y As Single, ByVal DragState As fmDragState, ByVal Effect As MSForms.ReturnEffect, ByVal Shift As fmShiftState)

For TabStrip
Private Sub object_BeforeDragOver( index As Long, ByVal Cancel As MSForms.ReturnBoolean, ByVal Data As DataObject, ByVal X As Single, ByVal Y As Single, ByVal DragState As fmDragState, ByVal Effect As MSForms.ReturnEffect, ByVal Shift As fmShiftState)

For other controls
Private Sub object_BeforeDragOver( ByVal Cancel As MSForms.ReturnBoolean, ByVal Data As DataObject, ByVal X As Single, ByVal Y As Single, ByVal DragState As fmDragState, ByVal Effect As MSForms.ReturnEffect, ByVal Shift As fmShiftState)

The BeforeDragOver event syntax has these parts:

Part | Description
object | Required. A valid object name.
index | Required. The index of the Page in a MultiPage that the drag-and-drop operation will affect.
Cancel | Required. Event status. False indicates that the control should handle the event (default). True indicates the application handles the event.
ctrl | Required. The control being dragged over.
Data | Required. Data that is dragged in a drag-and-drop operation. The data is packaged in a DataObject.
X, Y | Required. The horizontal and vertical coordinates of the control's position. Both coordinates are measured in points. X is measured from the left edge of the control; Y is measured from the top of the control..
DragState | Required. Transition state of the data being dragged.
Effect | Required. Operations supported by the drop source.
Shift | Required. Specifies the state of SHIFT, CTRL, and ALT.

Settings

The settings for DragState are:

Constant | Value | Description
fmDragStateEnter | 0 | Mouse pointer is within range of a target.
fmDragStateLeave | 1 | Mouse pointer is outside the range of a target.
fmDragStateOver | 2 | Mouse pointer is at a new position, but remains within range of the same target.

The settings for Effect are:

Constant | Value | Description
fmDropEffectNone | 0 | Does not copy or move the drop source to the drop target.
fmDropEffectCopy | 1 | Copies the drop source to the drop target.
fmDropEffectMove | 2 | Moves the drop source to the drop target.
fmDropEffectCopyOrMove | 3 | Copies or moves the drop source to the drop target.

The settings for Shift are:

Constant | Value | Description
fmShiftMask | 1 | SHIFT was pressed.
fmCtrlMask | 2 | CTRL was pressed.
fmAltMask | 4 | ALT was pressed.

Remarks

Use this event to monitor the mouse pointer as it enters, leaves, or rests directly over a valid target. When a drag-and-drop operation is in progress, the system initiates this event when the user moves the mouse, or presses or releases the mouse button or buttons. The mouse pointer position determines the target object that receives this event. You can determine the state of the mouse pointer by examining the DragState argument.

When a control handles this event, you can use the Effect argument to identify the drag-and-drop action to perform. When Effect is set to fmDropEffectCopyOrMove, the drop source supports a copy (fmDropEffectCopy), move (fmDropEffectMove), or a cancel (fmDropEffectNone) operation.

When Effect is set to fmDropEffectCopy, the drop source supports a copy or a cancel (fmDropEffectNone) operation.

When Effect is set to fmDropEffectMove, the drop source supports a move or a cancel (fmDropEffectNone) operation.

When Effect is set to fmDropEffectNone. the drop source supports a cancel operation.

Most controls do not support drag-and-drop while Cancel is False, which is the default setting. This means the control rejects attempts to drag or drop anything on the control, and the control does not initiate the BeforeDropOrPaste event. The TextBox and ComboBox controls are exceptions to this; these controls support drag-and-drop operations even when Cancel is False.


BeforeDropOrPaste Event

 Copy code hover
[image]

BeforeDropOrPaste Event
Send feedback

Occurs when the user is about to drop or paste data onto an object.

Syntax

For Frame
Private Sub object_BeforeDropOrPaste( ByVal Cancel As MSForms.ReturnBoolean, ctrl As Control, ByVal Action As fmAction, ByVal Data As DataObject, ByVal X As Single, ByVal Y As Single, ByVal Effect As MSForms.ReturnEffect, ByVal Shift As fmShiftState)

For MultiPage
Private Sub object_BeforeDropOrPaste( index As Long, ByVal Cancel As MSForms.ReturnBoolean, ctrl As Control, ByVal Action As fmAction, ByVal Data As DataObject, ByVal X As Single, ByVal Y As Single, ByVal Effect As MSForms.ReturnEffect, ByVal Shift As fmShiftState)

For TabStrip
Private Sub object_BeforeDropOrPaste( index As Long, ByVal Cancel As MSForms.ReturnBoolean, ByVal Action As fmAction, ByVal Data As DataObject, ByVal X As Single, ByVal Y As Single, ByVal Effect As MSForms.ReturnEffect, ByVal Shift As fmShiftState)

For other controls
Private Sub object_BeforeDropOrPaste( ByVal Cancel As MSForms.ReturnBoolean, ByVal Action As fmAction, ByVal Data As DataObject, ByVal X As Single, ByVal Y As Single, ByVal Effect As MSForms.ReturnEffect, ByVal Shift As fmShiftState)

The BeforeDropOrPaste event syntax has these parts:

Part | Description
object | Required. A valid object name.
index | Required. The index of the Page in a MultiPage that the drop or paste operation will affect.
Cancel | Required. Event status. False indicates that the control should handle the event (default). True indicates the application handles the event.
ctrl | Required. The target control.
Action | Required. Indicates the result, based on the current keyboard settings, of the pending drag-and-drop operation.
Data | Required. Data that is dragged in a drag-and-drop operation. The data is packaged in a DataObject.
X, Y | Required. The horizontal and vertical position of the mouse pointer when the drop occurs. Both coordinates are measured in points. X is measured from the left edge of the control; Y is measured from the top of the control..
Effect | Required. Effect of the drag-and-drop operation on the target control.
Shift | Required. Specifies the state of SHIFT, CTRL, and ALT.

Settings

The settings for Action are:

Constant | Value | Description
fmActionPaste | 2 | Pastes the selected object into the drop target.
fmActionDragDrop | 3 | Indicates the user has dragged the object from its source to the drop target and dropped it on the drop target.

The settings for Effect are:

Constant | Value | Description
fmDropEffectNone | 0 | Does not copy or move the drop source to the drop target.
fmDropEffectCopy | 1 | Copies the drop source to the drop target.
fmDropEffectMove | 2 | Moves the drop source to the drop target.
fmDropEffectCopyOrMove | 3 | Copies or moves the drop source to the drop target.

The settings for Shift are:

Constant | Value | Description
fmShiftMask | 1 | SHIFT was pressed.
fmCtrlMask | 2 | CTRL was pressed.
fmAltMask | 4 | ALT was pressed.

Remarks

For a MultiPage or TabStrip, Visual Basic for Applications initiates this event when it transfers a data object to the control.

For other controls, the system initiates this event immediately prior to the drop or paste operation.

When a control handles this event, you can update the Action argument to identify the drag-and-drop action to perform. When Effect is set to fmDropEffectCopyOrMove, you can assign Action to fmDropEffectNone, fmDropEffectCopy, or fmDropEffectMove. When Effect is set to fmDropEffectCopy or fmDropEffectMove, you can reassign Action to fmDropEffectNone. You cannot reassign Action when Effect is set to fmDropEffectNone.


BeforeUpdate Event

 Copy code hover
[image]

BeforeUpdate Event
Send feedback

Occurs before data in a control is changed.

Syntax

Private Sub object_BeforeUpdate( ByVal Cancel As MSForms.ReturnBoolean)

The BeforeUpdate event syntax has these parts:

Part | Description
object | Required. A valid object.
Cancel | Required. Event status. False indicates that the control should handle the event (default). True cancels the update and indicates the application should handle the event.

Remarks

The BeforeUpdate event occurs regardless of whether the control is bound (that is, when the RowSource property specifies a data source for the control). This event occurs before the AfterUpdate and Exit events for the control (and before the Enter event for the next control that receives focus).

If you set the Cancel argument to True, the focus remains on the control and neither the AfterUpdate event nor the Exit event occurs.


Change Event

 Copy code hover
[image]

Change Event
Send feedback

Occurs when the Value property changes.

Syntax

Private Sub object_Change( )

The Change event syntax has these parts:

Part | Description
object | Required. A valid object.

Settings

The Change event occurs when the setting of the Value property changes, regardless of whether the change results from execution of code or a user action in the interface.

Here are some examples of actions that change the Value property:

  • Clicking a CheckBox, OptionButton, or ToggleButton.

  • Entering or selecting a new text value for a ComboBox, ListBox, or TextBox.

  • Selecting a different tab on a TabStrip.

  • Moving the scroll box in a ScrollBar.

  • Clicking the up arrow or down arrow on a SpinButton.

  • Selecting a different page on a MultiPage.

Remarks

The Change event procedure can synchronize or coordinate data displayed among controls. For example, you can use the Change event procedure of a ScrollBar to update the contents of a TextBox that displays the value of the ScrollBar. Or you can use a Change event procedure to display data and formulas in a work area and results in another area.

Note Note

In some cases, the Click event may also occur when the Value property changes. However, using the Change event is the preferred technique for detecting a new value for a property.


Click Event

 Copy code hover
[image]

Click Event
Send feedback

Occurs in one of two cases:

  • The user clicks a control with the mouse.

  • The user definitively selects a value for a control with more than one possible value.

Syntax

For MultiPage, TabStrip
Private Sub object_Click( index As Long)

For all other controls
Private Sub object_Click( )

The Click event syntax has these parts:

Part | Description
object | Required. A valid object.
index | Required. The index of the page or tab in a MultiPage or TabStrip associated with this event.

Remarks

Of the two cases where the Click event occurs, the first case applies to the CommandButton, Frame, Image, Label, ScrollBar, and SpinButton. The second case applies to the CheckBox, ComboBox, ListBox, MultiPage, TabStrip, and ToggleButton. It also applies to an OptionButton when the value changes to True.

The following are examples of actions that initiate the Click event:

  • Clicking a blank area of a form or a disabled control (other than a list box) on the form.

  • Clicking a CommandButton. If the command button doesn't already have the focus, the Enter event occurs before the Click event.

  • Pressing the SPACEBAR when a CommandButton has the focus.

  • Clicking a control.

  • Pressing ENTER on a form that has a command button whose Default property is set to True, as long as no other command button has the focus.

  • Pressing ESC on a form that has a command button whose Cancel property is set to True, as long as no other command button has the focus.

  • Pressing a control's accelerator key.

When the Click event results from clicking a control, the sequence of events leading to the Click event is:

  1. MouseDown

  2. MouseUp

  3. Click

For some controls, the Click event occurs when the Value property changes. However, using the Change event is the preferred technique for detecting a new value for a property. The following are examples of actions that initiate the Click event due to assigning a new value to a control:

  • Clicking a different page or tab in a MultiPage or TabStrip. The Value property for these controls reflects the current Page or Tab. Clicking the current page or tab does not change the control's value and does not initiate the Click event.

  • Clicking a CheckBox or ToggleButton, pressing the SPACEBAR when one of these controls has the focus, pressing the accelerator key for one of these controls, or changing the value of the control in code.

  • Changing the value of an OptionButton to True. Setting one OptionButton in a group to True sets all other buttons in the group to False, but the Click event occurs only for the button whose value changes to True.

  • Selecting a value for a ComboBox or ListBox so that it unquestionably matches an item in the control's drop-down list. For example, if a list is not sorted, the first match for characters typed in the edit region may not be the only match in the list, so choosing such a value does not initiate the Click event. In a sorted list, you can use entry-matching to ensure that a selected value is a unique match for text the user types.

The Click event is not initiated when Value is set to Null.

Note Note

Clicking changes the value of a control, thus it initiates the Click event. When you right-click, the value of the control does not change, so it does not initiate the Click event.


DblClick Event

 Copy code hover
[image]

DblClick Event
Send feedback

Occurs when the user points to an object and then clicks a mouse button twice.

Syntax

For MultiPage, TabStrip
Private Sub object_DblClick( index As Long, ByVal Cancel As MSForms.ReturnBoolean)

For other controls
Private Sub object_DblClick( ByVal Cancel As MSForms.ReturnBoolean)

The DblClick event syntax has these parts:

Part | Description
object | Required. A valid object.
index | Required. The position of a Page or Tab object within a Pages or Tabs collection.
Cancel | Required. Event status. False indicates that the control should handle the event (default). True indicates the application handles the event.

Remarks

For this event to occur, the two clicks must occur within the time span specified by the system's double-click speed setting.

For controls that support Click, the following sequence of events leads to the DblClick event:

  1. MouseDown

  2. MouseUp

  3. Click

  4. DblClick

If a control, such as TextBox, does not support Click, Click is omitted fom the order of events leading to the DblClick event.

If the return value of Cancel is True when the user clicks twice, the control ignores the second click. This is useful if the second click reverses the effect of the first, such as double-clicking a toggle button. The Cancel argument allows your form to ignore the second click, so that either clicking or double-clicking the button has the same effect.


DropButtonClick Event

 Copy code hover
[image]

DropButtonClick Event
Send feedback

Occurs whenever the drop-down list appears or disappears.

Syntax

Private Sub object_DropButtonClick( )

The DropButtonClick event syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

You can initiate the DropButtonClick event through code or by taking certain actions in the user interface.

In code, calling the DropDown method initiates the DropButtonClick event.

In the user interface, any of the following actions initiates the event:

  • Clicking the drop-down button on the control.

  • Pressing F4.

Any of the above actions, in code or in the interface, cause the drop-down box to appear on the control. The system initiates the DropButtonClick event when the drop-down box goes away.


Enter, Exit Events

 Copy code hover
[image]

Enter, Exit Events
Send feedback

Enter occurs before a control actually receives the focus from a control on the same form. Exit occurs immediately before a control loses the focus to another control on the same form.

Syntax

Private Sub object_Enter( )

Private Sub object_Exit( ByVal Cancel As MSForms.ReturnBoolean)

The Enter and Exit event syntaxes have these parts:

Part | Description
object | Required. A valid object name.
Cancel | Required. Event status. False indicates that the control should handle the event (default). True indicates the application handles the event and the focus should remain at the current control.

Remarks

The Enter and Exit events are similar to the GotFocus and LostFocus events in Visual Basic. Unlike GotFocus and LostFocus, the Enter and Exit events don't occur when a form receives or loses the focus.

For example, suppose you select the check box that initiates the Enter event. If you then select another control in the same form, the Exit event is initiated for the check box (because focus is moving to a different object in the same form) and then the Enter event occurs for the second control on the form.

Because the Enter event occurs before the focus moves to a particular control, you can use an Enter event procedure to display instructions; for example, you could use a macro or event procedure to display a small form or message box identifying the type of data the control typically contains.

Note Note

To prevent the control from losing focus, assign True to the Cancel argument of the Exit event.


Error Event

 Copy code hover
[image]

Error Event
Send feedback

Occurs when a control detects an error and cannot return the error information to a calling program.

Syntax

For MultiPage
Private Sub object_Error( index As Long, ByVal Number As Integer, ByVal Description As MSForms.ReturnString, ByVal SCode As SCode, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, ByVal CancelDisplay As MSForms.ReturnBoolean)

For other controls
Private Sub object_Error( ByVal Number As Integer, ByVal Description As MSForms.ReturnString, ByVal SCode As SCode, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, ByVal CancelDisplay As MSForms.ReturnBoolean)

The Error event syntax has these parts:

Part | Description
object | Required. A valid object name.
index | Required. The index of the page in a MultiPage associated with this event.
Number | Required. Specifies a unique value that the control uses to identify the error.
Description | Required. A textual description of the error.
SCode | Required. Specifies the OLE status code for the error. The low-order 16 bits specify a value that is identical to the Number argument.
Source | Required. The string that identifies the control which initiated the event.
HelpFile | Required. Specifies a fully qualified path name for the Help file that describes the error.
HelpContext | Required. Specifies the context ID of the Help file topic that contains a description of the error.
CancelDisplay | Required. Specifies whether to display the error string in a message box.

Remarks

The code written for the Error event determines how the control responds to the error condition.

The ability to handle error conditions varies from one application to another. The Error event is initiated when an error occurs that the application is not equipped to handle.


KeyDown, KeyUp Events

 Copy code hover
[image]

KeyDown, KeyUp Events
Send feedback

Occur in sequence when a user presses and releases a key. KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.

Syntax

Private Sub object_KeyDown( ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As fmShiftState)

Private Sub object_KeyUp( ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As fmShiftState)

The KeyDown and KeyUp event syntaxes have these parts:

Part | Description
object | Required. A valid object name.
KeyCode | Required. An integer that represents the key code of the key that was pressed or released.
Shift | Required. The state of SHIFT, CTRL, and ALT.

Settings

The settings for Shift are:

Constant | Value | Description
fmShiftMask | 1 | SHIFT was pressed.
fmCtrlMask | 2 | CTRL was pressed.
fmAltMask | 4 | ALT was pressed.

Remarks

The KeyDown event occurs when the user presses a key on a running form while that form or a control on it has the focus. The KeyDown and KeyPress events alternate repeatedly until the user releases the key, at which time the KeyUp event occurs. The form or control with the focus receives all keystrokes. A form can have the focus only if it has no controls or all its visible controls are disabled.

These events also occur if you send a keystroke to a form or control using either the SendKeys action in a macro or the SendKeys Statement in Visual Basic.

The KeyDown and KeyUp events are typically used to recognize or distinguish between:

  • Extended character keys, such as function keys.

  • Navigation keys, such as HOME, END, PAGEUP, PAGEDOWN, UP ARROW, DOWN ARROW, RIGHT ARROW, LEFT ARROW, and TAB.

  • Combinations of keys and standard keyboard modifiers (SHIFT, CTRL, or ALT).

  • The numeric keypad and keyboard number keys.

The KeyDown and KeyUp events do not occur under the following circumstances:

  • The user presses enter on a form with a command button whose Default property is set to True.

  • The user presses esc on a form with a command button whose Cancel property is set to True.

The KeyDown and KeyPress events occur when you press or send an ANSI key. The KeyUp event occurs after any event for a control caused by pressing or sending the key. If a keystroke causes the focus to move from one control to another control, the KeyDown event occurs for the first control, while the KeyPress and KeyUp events occur for the second control.

The sequence of keyboard-related events is:

  1. KeyDown

  2. KeyPress

  3. KeyUp

Note Note

The KeyDown and KeyUp events apply only to forms and controls on a form. To interpret ANSI characters or to find out the ANSI character corresponding to the key pressed, use the KeyPress event.


KeyPress Event

 Copy code hover
[image]

KeyPress Event
Send feedback

Occurs when the user presses an ANSI key.

Syntax

Private Sub object_KeyPress( ByVal KeyANSI As MSForms.ReturnInteger)

The KeyPress event syntax has these parts:

Part | Description
object | Required. A valid object.
KeyANSI | Required. An integer value that represents a standard numeric ANSI key code.

Remarks

The KeyPress event occurs when the user presses a key that produces a typeable character (an ANSI key) on a running form while the form or a control on it has the focus. The event can occur either before or after the key is released. This event also occurs if you send an ANSI keystroke to a form or control using either the SendKeys action in a macro or the SendKeys Statement in Visual Basic.

A KeyPress event can occur when any of the following keys are pressed:

  • Any printable keyboard character.

  • CTRL combined with a character from the standard alphabet.

  • CTRL combined with any special character.

  • BACKSPACE.

  • ESC.

A KeyPress event does not occur under the following conditions:

  • Pressing TAB.

  • Pressing ENTER.

  • Pressing an arrow key.

  • When a keystroke causes the focus to move from one control to another.

Note Note

BACKSPACE is part of the ANSI character set, but DELETE is not. Deleting a character in a control using BACKSPACE causes a KeyPress event; deleting a character using DELETE doesn't.

When a user holds down a key that produces an ANSI keycode, the KeyDown and KeyPress events alternate repeatedly. When the user releases the key, the KeyUp event occurs. The form or control with the focus receives all keystrokes. A form can have the focus only if it has no controls, or if all its visible controls are disabled.

The default action for the KeyPress event is to process the event code that corresponds to the key that was pressed. KeyANSI indicates the ANSI character that corresponds to the pressed key or key combination. The KeyPress event interprets the uppercase and lowercase of each character as separate key codes and, therefore, as two separate characters.

To respond to the physical state of the keyboard, or to handle keystrokes not recognized by the KeyPress event, such as function keys, navigation keys, and any combinations of these with keyboard modifiers (ALT, SHIFT, or CTRL), use the KeyDown and KeyUp event procedures.

The sequence of keyboard-related events is:

  1. KeyDown

  2. KeyPress

  3. KeyUp


Layout Event

 Copy code hover
[image]

Layout Event
Send feedback

Occurs when a form, Frame, or MultiPage changes size.

Syntax

For MultiPage
Private Sub object_Layout( index As Long)

For all other controls
Private Sub object_Layout( )

The Layout event syntax has these parts:

Part | Description
object | Required. A valid object.
index | Required. The index of the page in a MultiPage that changed size.

Remarks

The default action of the layout event is to calculate new positions of controls and to repaint the screen.

A user can initiate the Layout event by changing the size of a control.

For controls that support the AutoSize property, the Layout event is initiated when AutoSize changes the size of the control. This occurs when the user changes the value of a property that affects the size of a control. For example, increasing the Font size of a TextBox or Label can significantly change the dimensions of the control and initiate a Layout event.


MouseDown, MouseUp Events

 Copy code hover
[image]

MouseDown, MouseUp Events
Send feedback

Occur when the user clicks a mouse button. MouseDown occurs when the user presses the mouse button; MouseUp occurs when the user releases the mouse button.

Syntax

For MultiPage, TabStrip
Private Sub object_MouseDown( index As Long, ByVal Button As fmButton, ByVal Shift As fmShiftState, ByVal X As Single, ByVal Y As Single)

Private Sub object_MouseUp( index As Long, ByVal Button As fmButton, ByVal Shift As fmShiftState, ByVal X As Single, ByVal Y As Single)

For other controls
Private Sub object_MouseDown( ByVal Button As fmButton, ByVal Shift As fmShiftState, ByVal X As Single, ByVal Y As Single)

Private Sub object_MouseUp( ByVal Button As fmButton, ByVal Shift As fmShiftState, ByVal X As Single, ByVal Y As Single)

The MouseDown and MouseUp event syntaxes have these parts:

Part | Description
object | Required. A valid object.
index | Required. The index of the page or tab in a MultiPage or TabStrip with the specified event.
Button | Required. An integer value that identifies which mouse button caused the event.
Shift | Required. The state of SHIFT, CTRL, and ALT.
X, Y | Required. The horizontal or vertical position, in points, from the left or top edge of the form, Frame, or Page.

Settings

The settings for Button are:

Constant | Value | Description
fmButtonLeft | 1 | The left button was pressed.
fmButtonRight | 2 | The right button was pressed.
fmButtonMiddle | 4 | The middle button was pressed.

The settings for Shift are:

Value | Description
1 | SHIFT was pressed.
2 | CTRL was pressed.
3 | SHIFT and CTRL were pressed.
4 | ALT was pressed.
5 | ALT and SHIFT were pressed.
6 | ALT and CTRL were pressed.
7 | ALT, SHIFT, and CTRL were pressed.

You can identify individual keyboard modifiers by using the following constants:

Constant | Value | Description
fmShiftMask | 1 | Mask to detect SHIFT.
fmCtrlMask | 2 | Mask to detect CTRL.
fmAltMask | 4 | Mask to detect ALT.

Remarks

For a MultiPage, the MouseDown event occurs when the user presses a mouse button over the control.

For a TabStrip, the index argument identifies the tab where the user clicked. An index of -1 indicates the user did not click a tab. For example, if there are no tabs in the upper right corner of the control, clicking in the upper right corner sets the index to -1.

For a form, the user can generate MouseDown and MouseUp events by pressing and releasing a mouse button in a blank area, record selector, or scroll bar on the form.

The sequence of mouse-related events is:

  1. MouseDown

  2. MouseUp

  3. Click

  4. DblClick

  5. MouseUp

MouseDown or MouseUp event procedures specify actions that occur when a mouse button is pressed or released. MouseDown and MouseUp events enable you to distinguish between the left, right, and middle mouse buttons. You can also write code for mouse-keyboard combinations that use the SHIFT, CTRL, and ALT keyboard modifiers.

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

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

Use the Shift argument to identify the state of SHIFT, CTRL, and ALT when the MouseDown or MouseUp event occurred. For example, if both CTRL and ALT are pressed, the value of Shift is 6.


MouseMove Event

 Copy code hover
[image]

MouseMove Event
Send feedback

Occurs when the user moves the mouse.

Syntax

For MultiPage, TabStrip
Private Sub object_MouseMove( index As Long, ByVal Button As fmButton, ByVal Shift As fmShiftState, ByVal X As Single, ByVal Y As Single)

For other controls
Private Sub object_MouseMove( ByVal Button As fmButton, ByVal Shift As fmShiftState, ByVal X As Single, ByVal Y As Single)

The MouseMove event syntax has these parts:

Part | Description
object | Required. A valid object name.
index | Required. The index of the page or tab in a MultiPage or TabStrip associated with this event.
Button | Required. An integer value that identifies the state of the mouse buttons.
Shift | Required. Specifies the state of SHIFT, CTRL, and ALT.
X, Y | Required. The horizontal or vertical position, measured in points, from the left or top edge of the control.

Settings

The index argument specifies which page or tab was clicked over. A -1 designates that the user did not click on any of the pages or tabs.

The settings for Button are:

Value | Description
0 | No button is pressed.
1 | The left button is pressed.
2 | The right button is pressed.
3 | The right and left buttons are pressed.
4 | The middle button is pressed.
5 | The middle and left buttons are pressed.
6 | The middle and right buttons are pressed.
7 | All three buttons are pressed.

The settings for Shift are:

Value | Description
1 | SHIFT was pressed.
2 | CTRL was pressed.
3 | SHIFT and CTRL were pressed.
4 | ALT was pressed.
5 | ALT and SHIFT were pressed.
6 | ALT and CTRL were pressed.
7 | ALT, SHIFT, and CTRL were pressed.

You can identify individual keyboard modifiers by using the following constants:

Constant | Value | Description
fmShiftMask | 1 | Mask to detect SHIFT.
fmCtrlMask | 2 | Mask to detect CTRL.
fmAltMask | 4 | Mask to detect ALT.

Remarks

The MouseMove event applies to forms, controls on a form, and labels.

MouseMove events are 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.

Moving a form can also generate a MouseMove event even if the mouse is stationary. MouseMove events are generated when the form moves underneath the pointer. If a macro or event procedure moves a form in response to a MouseMove event, the event can continually generate (cascade) MouseMove events.

If two controls are very close together, and you move the mouse pointer quickly over the space between them, the MouseMove event might not occur for that space. In such cases, you might need to respond to the MouseMove event in both controls.

You can use the value returned in the Button argument to identify the state of the mouse buttons.

Use the Shift argument to identify the state of SHIFT, CTRL, and ALT when the MouseMove event occurred. For example, if both CTRL and ALT are pressed, the value of Shift is 6.

Note Note

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


RemoveControl Event

 Copy code hover
[image]

RemoveControl Event
Send feedback

Occurs when a control is deleted from the container.

Syntax

For MultiPage
Private Sub object_RemoveControl( index As Long, ctrl As Control)

For all other controls
Private Sub object_RemoveControl( ctrl As Control)

The RemoveControl event syntax has these parts:

Part | Description
object | Required. A valid object name.
index | Required. The index of the page in a MultiPage that contained the deleted control.
ctrl | Required. The deleted control.

Remarks

This event occurs when a control is deleted from the form, not when a control is unloaded due to a form being closed.


Scroll Event

 Copy code hover
[image]

Scroll Event
Send feedback

Occurs when the scroll box is repositioned.

Syntax

For ScrollBar
Private Sub object_Scroll( )

For MultiPage
Private Sub object_Scroll( index As Long, ActionX As fmScrollAction, ActionY As fmScrollAction, ByVal RequestDx As Single, ByVal RequestDy As Single, ByVal ActualDx As MSForms.ReturnSingle, ByVal ActualDy As MSForms.ReturnSingle)

For Frame
Private Sub object_Scroll( ActionX As fmScrollAction, ActionY As fmScrollAction, ByVal RequestDx As Single, ByVal RequestDy As Single, ByVal ActualDx As MSForms.ReturnSingle, ByVal ActualDy As MSForms.ReturnSingle)

The Scroll event syntax has these parts:

Part | Description
object | Required. A valid object name.
index | Required. The index of the page in a MultiPage associated with this event.
ActionX | Required. The action that occurred in the horizontal direction.
ActionY | Required. The action that occurred in the vertical direction.
RequestDx | Required. The distance, in points, you want the scroll bar to move in the horizontal direction.
RequestDy | Required. The distance, in points, you want the scroll bar to move in the vertical direction.
ActualDx | Required. The distance, in points, the scroll bar travelled in the horizontal direction.
ActualDy | Required. The distance, in points, the scroll bar travelled in the vertical direction.

Settings

The settings for ActionX and ActionY are:

Constant | Value | Description
fmScrollActionNoChange | 0 | No change occurred.
fmScrollActionLineUp | 1 | A small distance up on a vertical scroll bar; a small distance to the left on a horizontal scroll bar. Movement is equivalent to pressing the up or left arrow keys on the keyboard to move the scroll bar.
fmScrollActionLineDown | 2 | A small distance down on a vertical scroll bar; a small distance to the right on a horizontal scroll bar. Movement is equivalent to pressing the down or right arrow keys on the keyboard to move the scroll bar.
fmScrollActionPageUp | 3 | One page up on a vertical scroll bar; one page to the left on a horizontal scroll bar. Movement is equivalent to pressing PAGE UP on the keyboard to move the scroll bar.
fmScrollActionPageDown | 4 | One page down on a vertical scroll bar; one page to the right on a horizontal scroll bar. Movement is equivalent to pressing PAGE DOWN on the keyboard to move the scroll bar.
fmScrollActionBegin | 5 | The top of a vertical scroll bar; the left end of a horizontal scroll bar.
fmScrollActionEnd | 6 | The bottom of a vertical scroll bar; the right end of a horizontal scroll bar.
fmScrollActionPropertyChange | 8 | The value of either the ScrollTop or the ScrollLeft property changed. The direction and amount of movement depend on which property was changed and on the new property value.
fmScrollActionControlRequest | 9 | A control asked its container to scroll. The amount of movement depends on the specific control and container involved.
fmScrollActionFocusRequest | 10 | The user moved to a different control. The amount of movement depends on the placement of the selected control, and generally has the effect of moving the selected control so it is completely visible to the user.

Remarks

The Scroll events associated with a form, Frame, or Page return the following arguments: ActionX, ActionY, ActualX, and ActualY. ActionX and ActionY identify the action that occurred. ActualX and ActualY identify the distance that the scroll box traveled.

The default action is to calculate the new position of the scroll box and then scroll to that position.

You can initiate a Scroll event by issuing a Scroll method for a form, Frame, or Page. Users can generate Scroll events by moving the scroll box.

The Scroll event associated with the stand-alone ScrollBar indicates that the user moved the scroll box in either direction. This event is not initiated when the value of the ScrollBar changes by code or by the user clicking on parts of the ScrollBar other than the scroll box.


SpinDown, SpinUp Events

 Copy code hover
[image]

SpinDown, SpinUp Events
Send feedback

SpinDown occurs when the user clicks the lower or left spin-button arrow. SpinUp occurs when the user clicks the upper or right spin-button arrow.

Syntax

Private Sub object_SpinDown( )

Private Sub object_SpinUp( )

The SpinDown and SpinUp event syntaxes have these parts:

Part | Description
object | Required. A valid object.

Remarks

The SpinDown event decreases the Value property. The SpinUp event increases Value.


Zoom Event

 Copy code hover
[image]

Zoom Event
Send feedback

Occurs when the value of the Zoom property changes.

Syntax

For Frame
Private Sub object_Zoom( Percent As Integer)

For MultiPage
Private Sub object_Zoom( index As Long, Percent As Integer)

The Zoom event syntax has these parts:

Part | Description
object | Required. A valid object name.
index | Required. The index of the page in a MultiPage associated with this event.
Percent | Required. The percentage the form is to be zoomed. Valid values range from 10 percent to 400 percent.

Remarks

The value of the Zoom property identifies how the size of the form or Page changes. The value of the property indicates how the size of the control should change relative to its current size. Values less than 100 reduce the displayed size of the form; values greater than 100 increase the displayed size of the form.

You can set this property to any integer from 10 to 400.


Examples (Microsoft Forms)

 Copy code hover
[image]

Examples (Microsoft Forms)
Send feedback

Published: June 15, 2012

In this section

  • Add, Cut, Paste Methods, Page Object, MultiPage Control Example

  • AddControl Event, Add Method Example

  • Alignment Property Example

  • AutoSize, MultiLine, WordWrap, ScrollBars Properties, TextBox Control Example

  • BackColor, BackStyle, BorderColor, BorderStyle, ForeColor, SpecialEffect Properties Example

  • CanUndo, CanRedo Properties, UndoAction, RedoAction Methods Example

  • CheckBox Control, Enabled, Locked Properties Example

  • Click Event, CommandButton Control, Accelerator, Caption Properties Example

  • ComboBox Control, AddItem Method, Picture, PicturePosition Properties Example

  • Controls Collection, Move Method Example

  • Copy, GetFromClipboard, GetText Methods, DataObject Object Example

  • Count Property Example

  • Cut, Paste Methods, TextBox Control Example

  • Cycle Property Example

  • DblClick Event, CanPaste Property, Paste, Copy Methods Example

  • DragBehavior, EnterFieldBehavior Properties Example

  • DropDown Method Example

  • Enabled, EnterFieldBehavior, SelLength, SelStart, SelText Properties Example

  • Enter, Exit Events, ActiveControl Property Example

  • EnterKeyBehavior, MultiLine Property Example

  • Font Object, Bold, Italic, Size, StrikeThrough, Underline, Weight Properties Example

  • GetFormat, GetText, SetText Methods Example

  • GroupName Property Example

  • Height, Width, Left, Top, ClientHeight, ClientWidth, ClientLeft, ClientTop Properties, TabStrip, Image Control Example

  • Index Property Example

  • InsideHeight, InsideWidth Properties Example

  • Item Method, OptionButton Control Example

  • KeyDown Event, TextBox Control, CurLine, CurTargetX, CurX, Text Properties Example

  • KeyPress Event Example

  • LargeChange, SmallChange Properties Example

  • Layout Event, LayoutEffect Property, Move Method Example

  • Layout Event, OldLeft, OldTop, OldHeight, OldWidth Properties Example

  • ListBox Control, AddItem, RemoveItem Methods, ListIndex, ListCount Properties Example

  • ListBox Control, BoundColumn Property Example

  • ListBox Control, BoundColumn, ControlSource, RowSource Properties Example

  • ListBox Control, Column, ColumnCount, List Properties Example

  • ListBox Control, ColumnCount, ColumnWidths Properties Example

  • ListBox Control, DataObject Object, MouseMove Event, StartDrag, SetText Methods Example

  • ListBox Control, List Property Example

  • ListRows Property Example

  • ListStyle, MultiSelect Properties Example

  • ListWidth Property Example

  • Locked, DropButtonStyle, ShowDropButtonWhen Properties Example

  • MatchEntry Property, OptionButton Control Example

  • MatchFound, MatchRequired Properties, Change Event, CheckBox Control Example

  • Max, Min, MaxLength Properties Example

  • Max, Min, Zoom Properties, Frame, ScrollBar Controls Example

  • MouseIcon, MousePointer Properties Example

  • Move Method Example

  • MultiSelect, Selected Properties Example

  • Name Property Example

  • Object Property Example

  • Page Object, CommandButton, MultiPage Controls, ControlTipText Property Example

  • Page Object, MultiPage Control, Add, Clear, Remove Methods Example

  • Page Object, Pages Collection, MultiPage Control, SelectedItem Property Example

  • Parent Property Example

  • Paste, PutInClipboard, SetText Methods Example

  • PictureAlignment Property Example

  • PictureSizeMode Property Example

  • ScrollBar Control, Scroll Event Example

  • ScrollBars, KeepScrollBarsVisible Properties Example

  • ScrollHeight, ScrollLeft, ScrollTop, ScrollWidth Properties Example

  • SelectedItem Property, TabStrip Control, Tab Object, Tabs Collection Example

  • SetFocus Method, LineCount, TextLength Properties Example

  • SpinDown, SpinUp Events, Delay Property Example

  • Style Property Example

  • Style Property, Label Control Example

  • TabFixedHeight, TabFixedWidth Properties Example

  • TabIndex Property Example

  • TabStop Property Example

  • Tag Property Example

  • TakeFocusOnClick Property Example

  • TextBox Control, AutoSize, Text Properties Example

  • TextBox Control, SetFocus Method, EnterFieldBehavior, HideSelection, MultiLine, Value Properties Example

  • TextColumn Property Example

  • TopIndex Property Example

  • TripleState Property, ToggleButton Control Example

  • Value Property Example

  • Zoom Event, Zoom Property, Label Control Example

  • ZOrder Method, TextBox Control Example


Add, Cut, Paste Methods, Page Object, MultiPage Control Example

 Copy code hover
[image]

Add, Cut, Paste Methods, Page Object, MultiPage Control Example
Send feedback

The following example uses the Add, Cut, and Paste methods to cut and paste a control from a Page of a MultiPage. The control involved in the cut and paste operations is dynamically added to the form.

This example assumes the user will add, then cut, then paste the new control.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Three CommandButton controls named CommandButton1 through CommandButton3.

  • A MultiPage named MultiPage1.

Copy code Copy code
Dim MyTextBox As Control

Private Sub CommandButton1_Click()
 Set MyTextBox = MultiPage1.Pages(MultiPage1.Value).Controls_
 .Add("MSForms.TextBox.1", "MyTextBox", Visible)
 CommandButton2.Enabled = True
 CommandButton1.Enabled = False
End Sub

Private Sub CommandButton2_Click()
 MultiPage1.Pages(MultiPage1.Value).Controls.Cut
 CommandButton3.Enabled = True
 CommandButton2.Enabled = False
End Sub

Private Sub CommandButton3_Click()
 Dim MyPage As Object
 Set MyPage = _
 MultiPage1.Pages.Item(MultiPage1.Value)

 MyPage.Paste
 CommandButton3.Enabled = False
End Sub

Private Sub UserForm_Initialize()
 CommandButton1.Caption = "Add"
 CommandButton2.Caption = "Cut"
 CommandButton3.Caption = "Paste"

 CommandButton1.Enabled = True
 CommandButton2.Enabled = False
 CommandButton3.Enabled = False
End Sub


AddControl Event, Add Method Example

 Copy code hover
[image]

AddControl Event, Add Method Example
Send feedback

The following example uses the Add method to add a control to a form at run time and uses the AddControl event as confirmation that the control was added.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A CommandButton named CommandButton1.

  • A Label named Label1.

Copy code Copy code
Dim Mycmd as Control
Private Sub CommandButton1_Click()

 Set Mycmd = Controls.Add("MSForms.CommandButton.1") ', CommandButton2, Visible)
 Mycmd.Left = 18
 Mycmd.Top = 150
 Mycmd.Width = 175
 Mycmd.Height = 20
 Mycmd.Caption = "This is fun." & Mycmd.Name

End Sub

Private Sub UserForm_AddControl(ByVal Control As _
 MSForms.Control)
 Label1.Caption = "Control was Added."
End Sub


Alignment Property Example

 Copy code hover
[image]

Alignment Property Example
Send feedback

The following example demonstrates the Alignment property used with several OptionButton controls. In this example, the user can change the alignment by clicking a ToggleButton.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains the following controls:

  • Two OptionButton controls named OptionButton1 and OptionButton2.

  • A ToggleButton named ToggleButton1.

Copy code Copy code
Private Sub UserForm_Initialize()
 OptionButton1.Alignment = fmAlignmentLeft
 OptionButton2.Alignment = fmAlignmentLeft

 OptionButton1.Caption = "Alignment with AutoSize"
 OptionButton2.Caption = "Choice 2"
 OptionButton1.AutoSize = True
 OptionButton2.AutoSize = True

 ToggleButton1.Caption = "Left Align"
 ToggleButton1.WordWrap = True
 ToggleButton1.Value = True
End Sub

Private Sub ToggleButton1_Click()
 If ToggleButton1.Value = True Then
 ToggleButton1.Caption = "Left Align"
 OptionButton1.Alignment = fmAlignmentLeft
 OptionButton2.Alignment = fmAlignmentLeft
 Else
 ToggleButton1.Caption = "Right Align"
 OptionButton1.Alignment = fmAlignmentRight
 OptionButton2.Alignment = fmAlignmentRight
 End If
End Sub


AutoSize, MultiLine, WordWrap, ScrollBars Properties, TextBox Control Example

 Copy code hover
[image]

AutoSize, MultiLine, WordWrap, ScrollBars Properties, TextBox Control Example
Send feedback

The following example demonstrates the MultiLine, WordWrap, and ScrollBars properties on a TextBox.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A TextBox named TextBox1.

  • Four ToggleButton controls named ToggleButton1 through ToggleButton4.

To see the entire text placed in the TextBox, set MultiLine and WordWrap to True by clicking the ToggleButton controls.

When MultiLine is True, you can enter new lines of text by pressing SHIFT+ENTER.

ScrollBars appears when you manually change the content of the TextBox.

Copy code Copy code
Private Sub UserForm_Initialize()
'Initialize TextBox properties and toggle buttons

 TextBox1.Text = "Type your text here. "
 & "Enter SHIFT+ENTER to move to a new line."

 TextBox1.AutoSize = False
 ToggleButton1.Caption = "AutoSize Off"
 ToggleButton1.Value = False
 ToggleButton1.AutoSize = True

 TextBox1.WordWrap = False
 ToggleButton2.Caption = "WordWrap Off"
 ToggleButton2.Value = False
 ToggleButton2.AutoSize = True

 TextBox1.ScrollBars = 0
 ToggleButton3.Caption = "ScrollBars Off"
 ToggleButton3.Value = False
 ToggleButton3.AutoSize = True

 TextBox1.MultiLine = False
 ToggleButton4.Caption = "Single Line"
 ToggleButton4.Value = False
 ToggleButton4.AutoSize = True
 End Sub

Private Sub ToggleButton1_Click()
'Set AutoSize property and associated ToggleButton

 If ToggleButton1.Value = True Then
 TextBox1.AutoSize = True
 ToggleButton1.Caption = "AutoSize On"
 Else
 TextBox1.AutoSize = False
 ToggleButton1.Caption = "AutoSize Off"
 End If
End Sub
Copy code Copy code
Private Sub ToggleButton2_Click()
'Set WordWrap property and associated ToggleButton

 If ToggleButton2.Value = True Then
 TextBox1.WordWrap = True
 ToggleButton2.Caption = "WordWrap On"
 Else
 TextBox1.WordWrap = False
 ToggleButton2.Caption = "WordWrap Off"
 End If
End Sub
Copy code Copy code
Private Sub ToggleButton3_Click()
'Set ScrollBars property and associated ToggleButton

 If ToggleButton3.Value = True Then
 TextBox1.ScrollBars = 3
 ToggleButton3.Caption = "ScrollBars On"
 Else
 TextBox1.ScrollBars = 0
 ToggleButton3.Caption = "ScrollBars Off"
 End If
End Sub
Copy code Copy code
Private Sub ToggleButton4_Click()
'Set MultiLine property and associated ToggleButton

 If ToggleButton4.Value = True Then
 TextBox1.MultiLine = True
 ToggleButton4.Caption = "Multiple Lines"
 Else
 TextBox1.MultiLine = False
 ToggleButton4.Caption = "Single Line"
 End If
End Sub


BackColor, BackStyle, BorderColor, BorderStyle, ForeColor, SpecialEffect Properties Example

 Copy code hover
[image]

BackColor, BackStyle, BorderColor, BorderStyle, ForeColor, SpecialEffect Properties Example
Send feedback

The following example demonstrates the BorderStyle and SpecialEffect properties, showing each border available through these properties. The example also demonstrates how to control color settings by using the BackColor, BackStyle, BorderColor, and ForeColor properties.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Six TextBox controls named TextBox1 through TextBox6.

  • Two ToggleButton controls named ToggleButton1 and ToggleButton2.

Copy code Copy code
Private Sub UserForm_Initialize()
'Initialize each TextBox with a border style or special effect,
'and foreground and background colors

'TextBox1 initially uses a borderstyle
TextBox1.Text = "BorderStyle-Single"
TextBox1.BorderStyle = fmBorderStyleSingle
TextBox1.BorderColor = RGB(255, 128, 128)
'Color - Salmon
TextBox1.ForeColor = RGB(255, 255, 0)
'Color - Yellow
TextBox1.BackColor = RGB(0, 128, 64)
'Color - Green #2

'TextBoxes 2 through 6 initially use special effects
TextBox2.Text = "Flat"
TextBox2.SpecialEffect = fmSpecialEffectFlat
TextBox2.ForeColor = RGB(64, 0, 0)
'Color - Brown
TextBox2.BackColor = RGB(0, 0, 255)
'Color - Blue

'Ensure the background style for TextBox2 is initially
'opaque.
TextBox2.BackStyle = fmBackStyleOpaque

TextBox3.Text = "Etched"
TextBox3.SpecialEffect = fmSpecialEffectEtched
TextBox3.ForeColor = RGB(128, 0, 255)
'Color - Purple
TextBox3.BackColor = RGB(0, 255, 255)
'Color - Cyan

'Define BorderColor for later use (when borderstyle=fmBorderStyleSingle)
TextBox3.BorderColor = RGB(0, 0, 0)
'Color - Black

TextBox4.Text = "Bump"
TextBox4.SpecialEffect = fmSpecialEffectBump
TextBox4.ForeColor = RGB(255, 0, 255)
'Color - Magenta
TextBox4.BackColor = RGB(0, 0, 100)
'Color - Navy blue

TextBox5.Text = "Raised"
TextBox5.SpecialEffect = fmSpecialEffectRaised
TextBox5.ForeColor = RGB(255, 0, 0)
'Color - Red
TextBox5.BackColor = RGB(128, 128, 128)
'Color - Gray

TextBox6.Text = "Sunken"
TextBox6.SpecialEffect = fmSpecialEffectSunken
TextBox6.ForeColor = RGB(0, 64, 0)
'Color - Olive
TextBox6.BackColor = RGB(0, 255, 0)
'Color - Green #1

ToggleButton1.Caption = "Swap styles"
ToggleButton2.Caption = "Transparent/Opaque " _
 & "background"
End Sub

Private Sub ToggleButton1_Click()

'Swap borders between TextBox1 and TextBox3
If ToggleButton1.Value = True Then
 'Change TextBox1 from BorderStyle to Etched
 TextBox1.Text = "Etched"
 TextBox1.SpecialEffect = fmSpecialEffectEtched

 'Change TextBox3 from Etched to BorderStyle
 TextBox3.Text = "BorderStyle-Single"
 TextBox3.BorderStyle = fmBorderStyleSingle
Else
 'Change TextBox1 back to BorderStyle
 TextBox1.Text = "BorderStyle-Single"
 TextBox1.BorderStyle = fmBorderStyleSingle

 'Change TextBox3 back to Etched
 TextBox3.Text = "Etched"
 TextBox3.SpecialEffect = fmSpecialEffectEtched
End If
End Sub
Copy code Copy code
Private Sub ToggleButton2_Click()
'Set background to Opaque or Transparent
If ToggleButton2.Value = True Then
 'Change TextBox2 to a transparent background
 TextBox2.BackStyle = fmBackStyleTransparent
Else
 'Change TextBox2 back to opaque background
 TextBox2.BackStyle = fmBackStyleOpaque
End If
End Sub


CanUndo, CanRedo Properties, UndoAction, RedoAction Methods Example

 Copy code hover
[image]

CanUndo, CanRedo Properties, UndoAction, RedoAction Methods Example
Send feedback

The following example demonstrates how to undo or redo text editing within a text box or within the text area of a ComboBox. This sample checks whether an undo or redo operation can occur and then performs the appropriate action. The sample uses the CanUndo and CanRedo properties, and the UndoAction and RedoAction methods.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A TextBox named TextBox1.

  • A ComboBox named ComboBox1.

  • Two CommandButton controls named CommandButton1 and CommandButton2.

Copy code Copy code
Private Sub CommandButton1_Click()
 If UserForm1.CanUndo = True Then
 UserForm1.UndoAction
 MsgBox "Undid IT"
 Else
 MsgBox "No undo performed."
 End If
End Sub

Private Sub CommandButton2_Click()
 If UserForm1.CanRedo = True Then
 UserForm1.RedoAction
 MsgBox "Redid IT"
 Else
 MsgBox "No redo performed."
 End If
End Sub

Private Sub UserForm_Initialize()
 TextBox1.Text = "Type your text here."

 ComboBox1.ColumnCount = 3
 ComboBox1.AddItem "Choice 1, column 1"
 ComboBox1.List(0, 1) = "Choice 1, column 2"
 ComboBox1.List(0, 2) = "Choice 1, column 3"

 CommandButton1.Caption = "Undo"
 CommandButton2.Caption = "Redo"
End Sub


CheckBox Control, Enabled, Locked Properties Example

 Copy code hover
[image]

CheckBox Control, Enabled, Locked Properties Example
Send feedback

The following example demonstrates the Enabled and Locked properties and how they complement each other. This example exposes each property independently with a CheckBox, so you observe the settings individually and combined. This example also includes a second TextBox so you can copy and paste information between the TextBox controls and verify the activities supported by the settings of these properties.

Note Note

You can copy the selection to the Clipboard using CTRL+C and paste using CTRL+V.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A TextBox named TextBox1.

  • Two CheckBox controls named CheckBox1 and CheckBox2.

  • A second TextBox named TextBox2.

Copy code Copy code
Private Sub CheckBox1_Change()
 TextBox2.Text = "TextBox2"
 TextBox1.Enabled = CheckBox1.Value
End Sub

Private Sub CheckBox2_Change()
 TextBox2.Text = "TextBox2"
 TextBox1.Locked = CheckBox2.Value
End Sub

Private Sub UserForm_Initialize()
 TextBox1.Text = "TextBox1"
 TextBox1.Enabled = True
 TextBox1.Locked = False

 CheckBox1.Caption = "Enabled"
 CheckBox1.Value = True

 CheckBox2.Caption = "Locked"
 CheckBox2.Value = False

 TextBox2.Text = "TextBox2"
End Sub


Click Event, CommandButton Control, Accelerator, Caption Properties Example

 Copy code hover
[image]

Click Event, CommandButton Control, Accelerator, Caption Properties Example
Send feedback

This example changes the Accelerator and Caption properties of a CommandButton each time the user clicks the button by using the mouse or the accelerator key. The Click event contains the code to change the Accelerator and Caption properties.

To try this example, paste the code into the Declarations section of a form containing a CommandButton named CommandButton1.

Copy code Copy code
Private Sub UserForm_Initialize()
 CommandButton1.Accelerator = "C"
 'Set Accelerator key to COMMAND + C
End Sub

Private Sub CommandButton1_Click ()
 If CommandButton1.Caption = "OK" Then
 'Check caption, then change it.
 CommandButton1.Caption = "Clicked"
 CommandButton1.Accelerator = "C"
 'Set Accelerator key to COMMAND + C
 Else
 CommandButton1.Caption = "OK"
 CommandButton1.Accelerator = "O"
 'Set Accelerator key to COMMAND + O
 End If
End Sub


ComboBox Control, AddItem Method, Picture, PicturePosition Properties Example

 Copy code hover
[image]

ComboBox Control, AddItem Method, Picture, PicturePosition Properties Example
Send feedback

The following example uses a ComboBox to show the picture placement options for a control. Each time the user clicks a list choice, the picture and caption are updated on the CommandButton. This code sample also uses the AddItem method to populate the ComboBox choices.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Label named Label1.

  • A CommandButton named CommandButton1.

  • A ComboBox named ComboBox1.

Copy code Copy code
Private Sub UserForm_Initialize()
 Label1.Left = 18
 Label1.Top = 12
 Label1.Height = 12
 Label1.Width = 190
 Label1.Caption = "Select picture placement " _
 & "relative to the caption."

 'Add list entries to combo box. The value of each
 'entry matches the corresponding ListIndex value
 'in the combo box.
 ComboBox1.AddItem "Left Top" 'ListIndex = 0
 ComboBox1.AddItem "Left Center" 'ListIndex = 1
 ComboBox1.AddItem "Left Bottom" 'ListIndex = 2
 ComboBox1.AddItem "Right Top" 'ListIndex = 3
 ComboBox1.AddItem "Right Center" 'ListIndex = 4
 ComboBox1.AddItem "Right Bottom" 'ListIndex = 5
 ComboBox1.AddItem "Above Left" 'ListIndex = 6
 ComboBox1.AddItem "Above Center" 'ListIndex = 7
 ComboBox1.AddItem "Above Right" 'ListIndex = 8
 ComboBox1.AddItem "Below Left" 'ListIndex = 9
 ComboBox1.AddItem "Below Center" 'ListIndex = 10
 ComboBox1.AddItem "Below Right" 'ListIndex = 11
 ComboBox1.AddItem "Centered" 'ListIndex = 12
 'Use drop-down list
 ComboBox1.Style = fmStyleDropDownList
 'Combo box values are ListIndex values
 ComboBox1.BoundColumn = 0
 'Set combo box to first entry
 ComboBox1.ListIndex = 0

 ComboBox1.Left = 18
 ComboBox1.Top = 36
 ComboBox1.Width = 90
 ComboBox1.ListWidth = 90

 'Initialize CommandButton1
 CommandButton1.Left = 230
 CommandButton1.Top = 36
 CommandButton1.Height = 120
 CommandButton1.Width = 120

 'Note: Be sure to refer to a bitmap file that is
 'present on your system, and to include the path
 'in the filename.
 CommandButton1.Picture = _
 LoadPicture("c:\windows\argyle.bmp")
 CommandButton1.PicturePosition = ComboBox1.Value
End Sub

Private Sub ComboBox1_Click()
 Select Case ComboBox1.Value
 Case 0 'Left Top
 CommandButton1.Caption = "Left Top"
 CommandButton1.PicturePosition = _
 fmPicturePositionLeftTop

 Case 1 'Left Center
 CommandButton1.Caption = "Left Center"
 CommandButton1.PicturePosition = _
 fmPicturePositionLeftCenter

 Case 2 'Left Bottom
 CommandButton1.Caption = "Left Bottom"
 CommandButton1.PicturePosition = _
 fmPicturePositionLeftBottom

 Case 3 'Right Top
 CommandButton1.Caption = "Right Top"
 CommandButton1.PicturePosition = _
 fmPicturePositionRightTop

 Case 4 'Right Center
 CommandButton1.Caption = "Right Center"
 CommandButton1.PicturePosition = _
 fmPicturePositionRightCenter

 Case 5 'Right Bottom
 CommandButton1.Caption = "Right Bottom"
 CommandButton1.PicturePosition = _
 fmPicturePositionRightBottom

 Case 6 'Above Left
 CommandButton1.Caption = "Above Left"
 CommandButton1.PicturePosition = _
 fmPicturePositionAboveLeft

 Case 7 'Above Center
 CommandButton1.Caption = "Above Center"
 CommandButton1.PicturePosition = _
 fmPicturePositionAboveCenter

 Case 8 'Above Right
 CommandButton1.Caption = "Above Right"
 CommandButton1.PicturePosition = _
 fmPicturePositionAboveRight

 Case 9 'Below Left
 CommandButton1.Caption = "Below Left"
 CommandButton1.PicturePosition = _
 fmPicturePositionBelowLeft

 Case 10 'Below Center
 CommandButton1.Caption = "Below Center"
 CommandButton1.PicturePosition = _
 fmPicturePositionBelowCenter

 Case 11 'Below Right
 CommandButton1.Caption = "Below Right"
 CommandButton1.PicturePosition = _
 fmPicturePositionBelowRight

 Case 12 'Centered
 CommandButton1.Caption = "Centered"
 CommandButton1.PicturePosition = _
 fmPicturePositionCenter

 End Select

End Sub


Controls Collection, Move Method Example

 Copy code hover
[image]

Controls Collection, Move Method Example
Send feedback

The following example accesses individual controls from the Controls collection using a For Each...Next loop. When the user presses CommandButton1, the other controls are placed in a column along the left edge of the form using the Move method.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains a CommandButton named CommandButton1 and several other controls.

Copy code Copy code
Dim CtrlHeight As Single
Dim CtrlTop As Single
Dim CtrlGap As Single

Private Sub CommandButton1_Click()
 Dim MyControl As Control
 CtrlTop = 5

 For Each MyControl In Controls
 If MyControl.Name = "CommandButton1" Then
 'Don't move or resize this control.
 Else
 'Move method using named arguments
 MyControl.Move Top:=CtrlTop, _
 Height:=CtrlHeight, Left:=5

 'Move method using unnamed arguments (left,
 'top, width, height)
 'MyControl.Move 5, CtrlTop, ,CtrlHeight

 'Calculate top coordinate for next control
 CtrlTop = CtrlTop + CtrlHeight + CtrlGap
 End If
 Next

End Sub
Copy code Copy code
Private Sub UserForm_Initialize()
 CtrlHeight = 20
 CtrlGap = 5

 CommandButton1.Caption = "Click to move controls"
 CommandButton1.AutoSize = True
 CommandButton1.Left = 120
 CommandButton1.Top = CtrlTop
End Sub


Copy, GetFromClipboard, GetText Methods, DataObject Object Example

 Copy code hover
[image]

Copy, GetFromClipboard, GetText Methods, DataObject Object Example
Send feedback

The following example demonstrates data movement from a TextBox to the Clipboard, from the Clipboard to a DataObject, and from a DataObject into another TextBox. The GetFromClipboard method transfers the data from the Clipboard to a DataObject. The Copy and GetText methods are also used.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Two TextBox controls named TextBox1 and TextBox2.

  • A CommandButton named CommandButton1.

Copy code Copy code
Dim MyData as DataObject

Private Sub CommandButton1_Click()
 'Need to select text before copying it to Clipboard
 TextBox1.SelStart = 0
 TextBox1.SelLength = TextBox1.TextLength
 TextBox1.Copy

 MyData.GetFromClipboard
 TextBox2.Text = MyData.GetText(1)
End Sub

Private Sub UserForm_Initialize()
 Set MyData = New DataObject
 TextBox1.Text = "Move this data to the " _
 & "Clipboard, to a DataObject, then to "
 & "TextBox2!"
End Sub


Count Property Example

 Copy code hover
[image]

Count Property Example
Send feedback

The following example displays the Count property of the Controls collection for the form, and the Count property identifying the number of pages and tabs of each MultiPage and TabStrip.

To use this example, copy this sample code to the Declarations portion of a form. The form can contain any number of controls, with the following restrictions:

  • Names of MultiPage controls must start with "MultiPage".

  • Names of TabStrip controls must start with "TabStrip".

Note Note

You can add pages to a MultiPage or add tabs to a TabStrip. In Windows, double-click the control, then right-click in the tab area of the control and choose New Page from the shortcut menu.
Copy code Copy code
Private Sub UserForm_Initialize()
 Dim MyControl As Control

 MsgBox "UserForm1.Controls.Count = " _
 & Controls.Count

 For Each MyControl In Controls
 If (MyControl.Name Like "MultiPage*") Then
 MsgBox MyControl.Name _
 & ".Pages.Count = " _
 & MyControl.Pages.Count
 ElseIf (MyControl.Name Like "TabStrip*") Then
 MsgBox MyControl.Name & ".Tabs.Count = " _
 & MyControl.Tabs.Count
 End If
 Next

End Sub


Cut, Paste Methods, TextBox Control Example

 Copy code hover
[image]

Cut, Paste Methods, TextBox Control Example
Send feedback

The following example uses the Cut and Paste methods to cut text from one TextBox and paste it into another TextBox.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Two TextBox controls named TextBox1 and TextBox2.

  • A CommandButton named CommandButton1.

Copy code Copy code
Private Sub UserForm_Initialize()
 TextBox1.Text = "From TextBox1!"
 TextBox2.Text = "Hello "

 CommandButton1.Caption = "Cut and Paste"
 CommandButton1.AutoSize = True
End Sub

Private Sub CommandButton1_Click()
 TextBox2.SelStart = 0
 TextBox2.SelLength = TextBox2.TextLength
 TextBox2.Cut

 TextBox1.SetFocus
 TextBox1.SelStart = 0

 TextBox1.Paste
 TextBox2.SelStart = 0
End Sub


Cycle Property Example

 Copy code hover
[image]

Cycle Property Example
Send feedback

The following example defines the Cycle property for a Frame and two Page objects in a MultiPage.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Frame named Frame1.

  • A MultiPage named MultiPage1 that contains two objects named Page1 and Page2.

  • Two CommandButton controls named CommandButton1 and CommandButton2.

In the form, the Frame, and each Page of the MultiPage, place a couple of controls, so you can see how Cycle affects the tab order of the Frame and MultiPage.

The user should tab through the controls to observe how Cycle affects the tab order. Pressing CommandButton1 extends the tab order to include controls in the Frame and Page objects. Pressing CommandButton2 restricts the tab order.

Copy code Copy code
Private Sub RestrictCycles()
'Limit tab order for the Frame and Page objects
 Frame1.Cycle = fmCycleCurrentForm
 MultiPage1.Page1.Cycle = fmCycleCurrentForm
 MultiPage1.Page2.Cycle = fmCycleCurrentForm
End Sub

Private Sub UserForm_Initialize()
 RestrictCycles
End Sub

Private Sub CommandButton1_Click()
'Extend tab order subforms (the Frame and Page
'objects)
 Frame1.Cycle = fmCycleAllForms
 MultiPage1.Page1.Cycle = fmCycleAllForms
 MultiPage1.Page2.Cycle = fmCycleAllForms
End Sub

Private Sub CommandButton2_Click()
 RestrictCycles
End Sub


DblClick Event, CanPaste Property, Paste, Copy Methods Example

 Copy code hover
[image]

DblClick Event, CanPaste Property, Paste, Copy Methods Example
Send feedback

The following example uses the CanPaste property and the Paste method to paste a ComboBox from the Clipboard to a Page of a MultiPage. This sample also uses the SetFocus and Copy methods to copy a control from the form to the Clipboard.

The user clicks CommandButton1 to copy the ComboBox to the Clipboard. The user double-clicks (using the DblClick event) CommandButton1 to paste the ComboBox to the MultiPage.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A TextBox named TextBox1.

  • A ComboBox named ComboBox1.

  • A MultiPage named MultiPage1.

  • A CommandButton named CommandButton1.

Note Note

This example also includes a subroutine to illustrate pasting text into a control.
Copy code Copy code
Private Sub UserForm_Initialize()
 ComboBox1.AddItem "It's a beautiful day!"

 CommandButton1.Caption = "Copy ComboBox to " _
 & "Clipboard"
 CommandButton1.AutoSize = True
End Sub

Private Sub MultiPage1_DblClick(ByVal Index As Long, _
 ByVal Cancel As MSForms.ReturnBoolean)
 If MultiPage1.Pages(MultiPage1.Value).CanPaste = _
 True
 Then
 MultiPage1.Pages(MultiPage1.Value).Paste
 Else
 TextBox1.Text = "Can't Paste"
 End If
End Sub

Private Sub CommandButton1_Click()
 UserForm1.ComboBox1.SetFocus
 UserForm1.Copy
End Sub

'Code for pasting text into a control
'Private Sub ComboBox1_DblClick(ByVal Cancel As _
 MSForms.ReturnBoolean)
' If ComboBox1.CanPaste = True Then
' ComboBox1.Paste
' Else
' TextBox1.Text = "Can't Paste"
' End If
'End Sub


DragBehavior, EnterFieldBehavior Properties Example

 Copy code hover
[image]

DragBehavior, EnterFieldBehavior Properties Example
Send feedback

The following example uses the DragBehavior and EnterFieldBehavior properties to demonstrate the different effects that you can provide when entering a control and when dragging information from one control to another.

The sample uses two TextBox controls. You can set DragBehavior and EnterFieldBehavior for each control and see the effects of dragging from one control to another.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A TextBox named TextBox1.

  • Two ToggleButton controls named ToggleButton1 and ToggleButton2. These controls are associated with TextBox1.

  • A TextBox named TextBox2.

  • Two ToggleButton controls named ToggleButton3 and ToggleButton4. These controls are associated with TextBox2.

Copy code Copy code
Private Sub UserForm_Initialize()
 TextBox1.Text = "Once upon a time in a land ...,"
 ToggleButton1.Value = True
 ToggleButton1.Caption = "Drag Enabled"
 ToggleButton1.WordWrap = True
 TextBox1.DragBehavior = fmDragBehaviorEnabled

 ToggleButton2.Value = True
 ToggleButton2.Caption = "Recall Selection"
 ToggleButton2.WordWrap = True
 TextBox1.EnterFieldBehavior = _
 fmEnterFieldBehaviorRecallSelection

 TextBox2.Text = "XXX, YYYY"
 ToggleButton3.Value = False
 ToggleButton3.Caption = "Drag Disabled"
 ToggleButton3.WordWrap = True
 TextBox2.DragBehavior = fmDragBehaviorDisabled

 ToggleButton4.Value = False
 ToggleButton4.Caption = "Select All"
 ToggleButton4.WordWrap = True
 TextBox2.EnterFieldBehavior = _
 fmEnterFieldBehaviorSelectAll
End Sub

Private Sub ToggleButton1_Click()
 If ToggleButton1.Value = True Then
 ToggleButton1.Caption = "Drag Enabled"
 TextBox1.DragBehavior = fmDragBehaviorEnabled
 Else
 ToggleButton1.Caption = "Drag Disabled"
 TextBox1.DragBehavior = fmDragBehaviorDisabled
 End If
End Sub

Private Sub ToggleButton2_Click()
 If ToggleButton2.Value = True Then
 ToggleButton2.Caption = "Recall Selection"
 TextBox1.EnterFieldBehavior = _
 fmEnterFieldBehaviorRecallSelection
 Else
 ToggleButton2.Caption = "Select All"
 TextBox1.EnterFieldBehavior = _
 fmEnterFieldBehaviorSelectAll
 End If
End Sub

Private Sub ToggleButton3_Click()
 If ToggleButton3.Value = True Then
 ToggleButton3.Caption = "Drag Enabled"
 TextBox2.DragBehavior = fmDragBehaviorEnabled
 Else
 ToggleButton3.Caption = "Drag Disabled"
 TextBox2.DragBehavior = fmDragBehaviorDisabled
 End If
End Sub

Private Sub ToggleButton4_Click()
 If ToggleButton4.Value = True Then
 ToggleButton4.Caption = "Recall Selection"
 TextBox2.EnterFieldBehavior = _
 fmEnterFieldBehaviorRecallSelection
 Else
 ToggleButton4.Caption = "Select All"
 TextBox2.EnterFieldBehavior = _
 fmEnterFieldBehaviorSelectAll
 End If
End Sub


DropDown Method Example

 Copy code hover
[image]

DropDown Method Example
Send feedback

The following example uses the DropDown method to display the list in a ComboBox. The user can display the list of a ComboBox by clicking the CommandButton.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A ComboBox named ComboBox1.

  • A CommandButton named CommandButton1.

Copy code Copy code
Private Sub CommandButton1_Click()
 ComboBox1.DropDown
End Sub

Private Sub UserForm_Initialize()
 ComboBox1.AddItem "Turkey"
 ComboBox1.AddItem "Chicken"
 ComboBox1.AddItem "Duck"
 ComboBox1.AddItem "Goose"
 ComboBox1.AddItem "Grouse"
End Sub


Enabled, EnterFieldBehavior, SelLength, SelStart, SelText Properties Example

 Copy code hover
[image]

Enabled, EnterFieldBehavior, SelLength, SelStart, SelText Properties Example
Send feedback

The following example tracks the selection-related properties (SelLength, SelStart, and SelText) that change as the user moves the insertion point and extends the selection using the keyboard. This example also uses the Enabled and EnterFieldBehavior properties.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • One large TextBox named TextBox1.

  • Three TextBox controls in a column named TextBox2 through TextBox4.

Copy code Copy code
Private Sub TextBox1_KeyUp(ByVal KeyCode As _
 MSForms.ReturnInteger, ByVal Shift As Integer)
 TextBox2.Text = TextBox1.SelStart
 TextBox3.Text = TextBox1.SelLength
 TextBox4.Text = TextBox1.SelText
End Sub
Copy code Copy code
Private Sub UserForm_Initialize()
 TextBox1.MultiLine = True
 TextBox1.EnterFieldBehavior = _
 fmEnterFieldBehaviorRecallSelection

 TextBox1.Text = "Type your text here. Use " _
 & "CTRL+ENTER to start a new line."
End Sub


Enter, Exit Events, ActiveControl Property Example

 Copy code hover
[image]

Enter, Exit Events, ActiveControl Property Example
Send feedback

The following example uses the ActiveControl property in a subroutine that tracks the controls a user visits. The Enter event for each control calls the TraceFocus subroutine to identify the control that has the focus.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains the following controls:

  • A ScrollBar named ScrollBar1.

  • A ListBox named ListBox1.

  • Two OptionButton controls named OptionButton1 and OptionButton2.

  • A Frame named Frame1.

Copy code Copy code
Dim MyControl As Control

Private Sub TraceFocus()
 ListBox1.AddItem ActiveControl.Name
 ListBox1.List(ListBox1.ListCount - 1, 1) = _
 ActiveControl.TabIndex
End Sub

Private Sub UserForm_Initialize()
 ListBox1.ColumnCount = 2
 ListBox1.AddItem "Controls Visited"
 ListBox1.List(0, 1) = "Control Index"
End Sub

Private Sub Frame1_Enter()
 TraceFocus
End Sub

Private Sub ListBox1_Enter()
 TraceFocus
End Sub

Private Sub OptionButton1_Enter()
 TraceFocus
End Sub

Private Sub OptionButton2_Enter()
 TraceFocus
End Sub

Private Sub ScrollBar1_Enter()
 TraceFocus
End Sub


EnterKeyBehavior, MultiLine Property Example

 Copy code hover
[image]

EnterKeyBehavior, MultiLine Property Example
Send feedback

The following example uses the EnterKeyBehavior property to control the effect of ENTER in a TextBox. In this example, the user can specify either a single-line or multiline TextBox.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A TextBox named TextBox1.

  • Two ToggleButton controls named ToggleButton1 and ToggleButton2.

Copy code Copy code
Private Sub UserForm_Initialize()
 TextBox1.EnterKeyBehavior = True
 ToggleButton1.Caption = "EnterKeyBehavior is True"
 ToggleButton1.Width = 70
 ToggleButton1.Value = True

 TextBox1.MultiLine = True
 ToggleButton2.Caption = "MultiLine is True"
 ToggleButton2.Width = 70
 ToggleButton2.Value = True

 TextBox1.Height = 100
 TextBox1.WordWrap = True
 TextBox1.Text = "Type your text here. If " _
 & "EnterKeyBehavior is True, " _
 & "press Enter to start a new line. Otherwise, press SHIFT+ENTER."
End Sub

Private Sub ToggleButton1_Click()
 If ToggleButton1.Value = True Then
 TextBox1.EnterKeyBehavior = True
 ToggleButton1.Caption = _
 "EnterKeyBehavior is True"
 Else
 TextBox1.EnterKeyBehavior = False
 ToggleButton1.Caption = _
 "EnterKeyBehavior is False"
 End If
End Sub

Private Sub ToggleButton2_Click()
 If ToggleButton2.Value = True Then
 TextBox1.MultiLine = True
 ToggleButton2.Caption = "MultiLine TextBox"
 Else
 TextBox1.MultiLine = False
 ToggleButton2.Caption = "Single-line TextBox"
 End If
End Sub


Font Object, Bold, Italic, Size, StrikeThrough, Underline, Weight Properties Example

 Copy code hover
[image]

Font Object, Bold, Italic, Size, StrikeThrough, Underline, Weight Properties Example
Send feedback

The following example demonstrates a Font object and the Bold, Italic, Size, StrikeThrough, Underline, and Weight properties related to fonts. You can manipulate font properties of an object directly or by using an alias, as this example also shows.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Label named Label1.

  • Four ToggleButton controls named ToggleButton1 through ToggleButton4.

  • A second Label and a TextBox named Label2 and TextBox1.

Copy code Copy code
Dim MyFont As StdFont

Private Sub ToggleButton1_Click()
 If ToggleButton1.Value = True Then
 MyFont.Bold = True
 'Using MyFont alias to control font
 ToggleButton1.Caption = "Bold On"
 MyFont.Size = 22
 'Increase the font size
 Else
 MyFont.Bold = False
 ToggleButton1.Caption = "Bold Off"
 MyFont.Size = 8
 'Return font size to initial size
 End If

 TextBox1.Text = Str(MyFont.Weight)
 'Bold and Weight are related
End Sub

Private Sub ToggleButton2_Click()
 If ToggleButton2.Value = True Then
 Label1.Font.Italic = True
 'Using Label1.Font directly
 ToggleButton2.Caption = "Italic On"
 Else
 Label1.Font.Italic = False
 ToggleButton2.Caption = "Italic Off"
 End If
End Sub

Private Sub ToggleButton3_Click()
 If ToggleButton3.Value = True Then
 Label1.Font.Strikethrough = True
 'Using Label1.Font directly
 ToggleButton3.Caption = "StrikeThrough On"
 Else
 Label1.Font.Strikethrough = False
 ToggleButton3.Caption = "StrikeThrough Off"
 End If
End Sub

Private Sub ToggleButton4_Click()
 If ToggleButton4.Value = True Then
 MyFont.Underline = True
 'Using MyFont alias for Label1.Font
 ToggleButton4.Caption = "Underline On"
 Else
 Label1.Font.Underline = False
 ToggleButton4.Caption = "Underline Off"
 End If
End Sub

Private Sub UserForm_Initialize()
 Set MyFont = Label1.Font

 ToggleButton1.Value = True
 ToggleButton1.Caption = "Bold On"

 Label1.AutoSize = True 'Set size of Label1
 Label1.AutoSize = False

 ToggleButton2.Value = False
 ToggleButton2.Caption = "Italic Off"

 ToggleButton3.Value = False
 ToggleButton3.Caption = "StrikeThrough Off"

 ToggleButton4.Value = False
 ToggleButton4.Caption = "Underline Off"

 Label2.Caption = "Font Weight"
 TextBox1.Text = Str(Label1.Font.Weight)
 TextBox1.Enabled = False
End Sub


GetFormat, GetText, SetText Methods Example

 Copy code hover
[image]

GetFormat, GetText, SetText Methods Example
Send feedback

The following example uses the GetFormat, GetText, and SetText methods to transfer text between a DataObject and the Clipboard.

The user types text into a TextBox and then can transfer it to a DataObject in a standard text format by clicking CommandButton1. Clicking CommandButton2 retrieves the text from the DataObject. Clicking CommandButton3 copies text from TextBox1 to the DataObject in a custom format. Clicking CommandButton4 retrieves the text from the DataObject in a custom format.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A TextBox named TextBox1.

  • Four CommandButton controls named CommandButton1 through CommandButton4.

  • A Label named Label1.

Copy code Copy code
Dim MyDataObject As DataObject

Private Sub CommandButton1_Click()
'Put standard format on Clipboard
 If TextBox1.TextLength > 0 Then
 Set MyDataObject = New DataObject
 MyDataObject.SetText TextBox1.Text
 Label1.Caption = "Put on D.O."
 CommandButton2.Enabled = True
 CommandButton4.Enabled = False
 End If
End Sub

Private Sub CommandButton2_Click()
'Get standard format from Clipboard
 If MyDataObject.GetFormat(1) = True Then
 Label1.Caption = "Std format - " _
 & MyDataObject.GetText(1)
 End If
End Sub

Private Sub CommandButton3_Click()
'Put custom format on Clipboard
 If TextBox1.TextLength > 0 Then
 Set MyDataObject = New DataObject
 MyDataObject.SetText TextBox1.Text, 233
 Label1.Caption = "Custom on D.O."
 CommandButton4.Enabled = True
 CommandButton2.Enabled = False
 End If
End Sub

Private Sub CommandButton4_Click()
'Get custom format from Clipboard
 If MyDataObject.GetFormat(233) = True Then
 Label1.Caption = "Cust format - " _
 & MyDataObject.GetText(233)
End If
End Sub

Private Sub UserForm_Initialize()
 CommandButton2.Enabled = False
 CommandButton4.Enabled = False
End Sub


GroupName Property Example

 Copy code hover
[image]

GroupName Property Example
Send feedback

The following example uses the GroupName property to create two groups of OptionButton controls on the same form.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains five OptionButton controls named OptionButton1 through OptionButton5.

Copy code Copy code
Private Sub UserForm_Initialize()
 OptionButton1.GroupName = "Widgets"
 OptionButton2.GroupName = "Widgets"
 OptionButton4.GroupName = "Widgets"

 OptionButton3.GroupName = "Gadgets-Group2"
 OptionButton5.GroupName = "Gadgets-Group2"
End Sub


Height, Width, Left, Top, ClientHeight, ClientWidth, ClientLeft, ClientTop Properties, TabStrip, Image Control Example

 Copy code hover
[image]

Height, Width, Left, Top, ClientHeight, ClientWidth, ClientLeft, ClientTop Properties, TabStrip, Image Control Example
Send feedback

The following example sets the dimensions of an Image to the size of a TabStrip's client area when the user clicks a CommandButton. This code sample uses the following properties: Height, Left, Top, Width, ClientHeight, ClientLeft, ClientTop, and ClientWidth.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A CommandButton named CommandButton1.

  • A TabStrip named TabStrip1.

  • An Image named Image1.

Copy code Copy code
Private Sub UserForm_Initialize()
 CommandButton1.Caption = "Size Image to Tab Area"
 CommandButton1.WordWrap = True
 CommandButton1.AutoSize = True
End Sub
Copy code Copy code
Private Sub CommandButton1_Click()
 Image1.ZOrder(fmFront)
'Place Image in front of TabStrip

'ClientLeft and ClientTop are measured from the edge
'of the TabStrip, not from the edges of the form
'containing the TabStrip.
 Image1.Left = TabStrip1.Left + TabStrip1.ClientLeft
 Image1.Top = TabStrip1.Top + TabStrip1.ClientTop
 Image1.Width = TabStrip1.ClientWidth
 Image1.Height = TabStrip1.ClientHeight

End Sub


Index Property Example

 Copy code hover
[image]

Index Property Example
Send feedback

The following example uses the Index property to change the order of the pages and tabs in a MultiPage and TabStrip. The user chooses CommandButton1 to move the third page and tab to the front of the MultiPage and TabStrip. The user chooses CommandButton2 to move the selected page and tab to the back of the MultiPage and TabStrip.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Two CommandButton controls named CommandButton1 and CommandButton2.

  • A MultiPage named MultiPage1.

  • A TabStrip named TabStrip1.

Copy code Copy code
Dim MyPageOrTab As Object

Private Sub CommandButton1_Click()
'Move third page and tab to front of control
 MultiPage1.page3.Index = 0
 TabStrip1.Tab3.Index = 0
End Sub

Private Sub CommandButton2_Click()
'Move selected page and tab to back of control
 Set MyPageOrObject = MultiPage1.SelectedItem
 MsgBox "MultiPage1.SelectedItem = " _
 & MultiPage1.SelectedItem.Name
 MyPageOrObject.Index = 4

 Set MyPageOrObject = TabStrip1.SelectedItem
 MsgBox "TabStrip1.SelectedItem = " _
 & TabStrip1.SelectedItem.Caption
 MyPageOrObject.Index = 4
End Sub

Private Sub UserForm_Initialize()
 MultiPage1.Width = 200
 MultiPage1.Pages.Add
 MultiPage1.Pages.Add
 MultiPage1.Pages.Add

 TabStrip1.Width = 200
 TabStrip1.Tabs.Add
 TabStrip1.Tabs.Add
 TabStrip1.Tabs.Add

 CommandButton1.Caption = _
 "Move third page/tab to front"
 CommandButton1.Width = 120

 CommandButton2.Caption = _
 "Move selected item to back"
 CommandButton2.Width = 120
 End Sub


InsideHeight, InsideWidth Properties Example

 Copy code hover
[image]

InsideHeight, InsideWidth Properties Example
Send feedback

The following example uses the InsideHeight and InsideWidth properties to resize a CommandButton. The user clicks the CommandButton to resize it.

Note Note

InsideHeight and InsideWidth are read-only properties.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A CommandButton named CommandButton1.

Copy code Copy code
Dim Resize As Single

Private Sub UserForm_Initialize()
 Resize = 0.75
 CommandButton1.Caption = "Resize Button"

End Sub

Private Sub CommandButton1_Click()
 CommandButton1.Move 10, 10, _
 UserForm1.InsideWidth * Resize, _
 UserForm1.InsideHeight * Resize
 CommandButton1.Caption = "Button resized " _
 & "using InsideHeight and InsideWidth!"
End Sub


Item Method, OptionButton Control Example

 Copy code hover
[image]

Item Method, OptionButton Control Example
Send feedback

The following example uses the Item method to access individual members of the Controls and Pages collections. The user chooses an option button for either the Controls collection or the MultiPage, and then clicks the CommandButton. The name of the appropriate control is returned in the Label.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A CommandButton named CommandButton1.

  • A Label named Label1.

  • Two OptionButton controls named OptionButton1 and OptionButton2.

  • A MultiPage named MultiPage1.

Copy code Copy code
Dim MyControl As Object
Dim ControlsIndex As Integer

Private Sub CommandButton1_Click()
 If OptionButton1.Value = True Then
 'Process Controls collection for UserForm
 Set MyControl = Controls.Item(ControlsIndex)
 Label1.Caption = MyControl.Name

 'Prepare index for next control on Userform
 ControlsIndex = ControlsIndex + 1
 If ControlsIndex >= Controls.Count Then
 ControlsIndex = 0
 End If

 ElseIf OptionButton2.Value = True Then
 'Process Current Page of Pages collection
 Set MyControl = MultiPage1.Pages _
 .Item(MultiPage1.Value)
 Label1.Caption = MyControl.Name
 End If
End Sub

Private Sub UserForm_Initialize()
 ControlsIndex = 0

 OptionButton1.Caption = "Controls Collection"
 OptionButton2.Caption = "Pages Collection"
 OptionButton1.Value = True

 CommandButton1.Caption = "Get Member Name"
End Sub


KeyDown Event, TextBox Control, CurLine, CurTargetX, CurX, Text Properties Example

 Copy code hover
[image]

KeyDown Event, TextBox Control, CurLine, CurTargetX, CurX, Text Properties Example
Send feedback

The following example tracks the CurLine, CurTargetX, and CurX property settings in a multiline TextBox. These settings change in the KeyUp event as the user types into the Text property, moves the insertion point, and extends the selection using the keyboard.

To use this example, follow these steps:

  1. Copy this sample code to the Declarations portion of a form.

  2. Add one large TextBox named TextBox1 to the form.

  3. Add three TextBox controls named TextBox2, TextBox3, and TextBox4 in a column.

Copy code Copy code
Private Sub TextBox1_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
 TextBox2.Text = TextBox1.CurLine
 TextBox3.Text = TextBox1.CurX
 TextBox4.Text = TextBox1.CurTargetX
End Sub
Copy code Copy code
Private Sub UserForm_Initialize()
 TextBox1.MultiLine = True

 TextBox1.Text = "Type your text here. User CTRL + ENTER to start a new line."
End Sub


KeyPress Event Example

 Copy code hover
[image]

KeyPress Event Example
Send feedback

The following example uses the KeyPress event to copy keystrokes from one TextBox to a second TextBox. The user types into the appropriately marked TextBox.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Two TextBox controls named TextBox1 and TextBox2.

Copy code Copy code
Private Sub TextBox1_KeyPress(ByVal KeyAscii As _
 MSForms.ReturnInteger)
 TextBox2.Text = TextBox2.Text & Chr(KeyAscii)

 'To handle keyboard combinations (using SHIFT,
 'CONTROL, OPTION, COMMAND, and another key),
 'or TAB or ENTER, use the KeyDown or KeyUp event.
End Sub

Private Sub UserForm_Initialize()
 Move 0, 0, 570, 380

 TextBox1.Move 30, 40, 220, 160
 TextBox1.MultiLine = True
 TextBox1.WordWrap = True
 TextBox1.Text = "Type text here."
 TextBox1.EnterKeyBehavior = True

 TextBox2.Move 298, 40, 220, 160
 TextBox2.MultiLine = True
 TextBox2.WordWrap = True
 TextBox2.Text = "Typed text copied here."
 TextBox2.Locked = True
 End Sub


LargeChange, SmallChange Properties Example

 Copy code hover
[image]

LargeChange, SmallChange Properties Example
Send feedback

The following example demonstrates the LargeChange and SmallChange properties when used with a stand-alone ScrollBar. The user can set the LargeChange and SmallChange values to any integer in the range of 0 to 100. This example also uses the MaxLength property to restrict the number of characters entered for the LargeChange and SmallChange values.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Label named Label1 and a TextBox named TextBox1.

  • A Label named Label2 and a TextBox named TextBox2.

  • A ScrollBar named ScrollBar1.

  • A Label named Label3.

Copy code Copy code
Dim TempNum As Integer

Private Sub ScrollBar1_Change()
 Label3.Caption = ScrollBar1.Value
End Sub

Private Sub TextBox1_Change()
 If IsNumeric(TextBox1.Text) Then
 TempNum = CInt(TextBox1.Text)
 If TempNum >= 0 And TempNum <= 100 Then
 ScrollBar1.SmallChange = TempNum
 Else
 TextBox1.Text = ScrollBar1.SmallChange
 End If
 Else
 TextBox1.Text = ScrollBar1.SmallChange
 End If
End Sub

Private Sub TextBox2_Change()
 If IsNumeric(TextBox2.Text) Then
 TempNum = CInt(TextBox2.Text)
 If TempNum >= 0 And TempNum <= 100 Then
 ScrollBar1.LargeChange = TempNum
 Else
 TextBox2.Text = ScrollBar1.LargeChange
 End If
 Else
 TextBox2.Text = ScrollBar1.LargeChange
 End If
End Sub

Private Sub UserForm_Initialize()
 ScrollBar1.Min = -1000
 ScrollBar1.Max = 1000

 Label1.Caption = "SmallChange 0 to 100"
 ScrollBar1.SmallChange = 1
 TextBox1.Text = ScrollBar1.SmallChange
 TextBox1.MaxLength = 3

 Label2.Caption = "LargeChange 0 to 100"
 ScrollBar1.LargeChange = 100
 TextBox2.Text = ScrollBar1.LargeChange
 TextBox2.MaxLength = 3

 ScrollBar1.Value = 0
 Label3.Caption = ScrollBar1.Value
End Sub


Layout Event, LayoutEffect Property, Move Method Example

 Copy code hover
[image]

Layout Event, LayoutEffect Property, Move Method Example
Send feedback

The following example moves a selected control on a form with the Move method, and uses the Layout event and LayoutEffect property to identify the control that moved (and changed the layout of the UserForm). The user clicks a control to move and then clicks the CommandButton. A message box displays the name of the control that is moving.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A TextBox named TextBox1.

  • A ComboBox named ComboBox1.

  • An OptionButton named OptionButton1.

  • A CommandButton named CommandButton1.

  • A ToggleButton named ToggleButton1.

Copy code Copy code
Private Sub UserForm_Initialize()
 CommandButton1.Caption = "Move current control"
 CommandButton1.AutoSize = True
 CommandButton1.TakeFocusOnClick = False

 ToggleButton1.Caption = "Use Layout Event"
 ToggleButton1.Value = True
End Sub

Private Sub CommandButton1_Click()
 If ActiveControl.Name = "ToggleButton1" Then
 'Keep it stationary
 Else
 'Move the control, using Layout event when
 'ToggleButton1.Value is True
 ActiveControl.Move 0, 0, , , _
 ToggleButton1.Value
 End If
End Sub

Private Sub UserForm_Layout()
 Dim MyControl As Control

 MsgBox "In the Layout Event"

 'Find the control that is moving.
 For Each MyControl In Controls
 If MyControl.LayoutEffect = _
 fmLayoutEffectInitiate Then
 MsgBox MyControl.Name & " is moving."
 Exit For
 End If
 Next
End Sub

Private Sub ToggleButton1_Click()
 If ToggleButton1.Value = True Then
 ToggleButton1.Caption = "Use Layout Event"
 Else
 ToggleButton1.Caption = "No Layout Event"
 End If
End Sub


Layout Event, OldLeft, OldTop, OldHeight, OldWidth Properties Example

 Copy code hover
[image]

Layout Event, OldLeft, OldTop, OldHeight, OldWidth Properties Example
Send feedback

The following example uses the OldLeft, OldTop, OldHeight, and OldWidth properties within the Layout event to keep a control at its current position and size. The user clicks the CommandButton labeled Move ComboBox to move the control, and then responds to a message box. The user can click the CommandButton labeled Reset ComboBox to reset the control for another repetition.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Two CommandButton controls named CommandButton1 and CommandButton2.

  • A ComboBox named ComboBox1.

Copy code Copy code
Dim Initialize As Integer
Dim ComboLeft, ComboTop, ComboWidth, _
 ComboHeight As Integer

Private Sub UserForm_Initialize()
 Initialize = 0
 CommandButton1.Caption = "Move ComboBox"
 CommandButton2.Caption = "Reset ComboBox"

 'Information for resetting ComboBox
 ComboLeft = ComboBox1.Left
 ComboTop = ComboBox1.Top
 ComboWidth = ComboBox1.Width
 ComboHeight = ComboBox1.Height
End Sub

Private Sub CommandButton1_Click()
 ComboBox1.Move 0, 0, , , True
End Sub

Private Sub UserForm_Layout()
 Dim MyControl As Control
 Dim MsgBoxResult As Integer
 'Suppress MsgBox on initial layout event.
 If Initialize = 0 Then
 Initialize = 1
 Exit Sub
 End If

 MsgBoxResult = MsgBox("In Layout event " _
 & "- Continue move?", vbYesNo)
 If MsgBoxResult = vbNo Then
 ComboBox1.Move ComboBox1.OldLeft, _
 ComboBox1.OldTop, ComboBox1.OldWidth, _
 ComboBox1.OldHeight
 End If
End Sub

Private Sub CommandButton2_Click()
 ComboBox1.Move ComboLeft, ComboTop, _
 ComboWidth, ComboHeight
End Sub


ListBox Control, AddItem, RemoveItem Methods, ListIndex, ListCount Properties Example

 Copy code hover
[image]

ListBox Control, AddItem, RemoveItem Methods, ListIndex, ListCount Properties Example
Send feedback

The following example adds and deletes the contents of a ListBox using the AddItem and RemoveItem methods, and the ListIndex and ListCount properties.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A ListBox named ListBox1.

  • Two CommandButton controls named CommandButton1 and CommandButton2.

Copy code Copy code
Dim EntryCount As Single

Private Sub CommandButton1_Click()
 EntryCount = EntryCount + 1
 ListBox1.AddItem (EntryCount & " - Selection")
End Sub
Copy code Copy code
Private Sub CommandButton2_Click()
 'Ensure ListBox contains list items
 If ListBox1.ListCount >= 1 Then
 'If no selection, choose last list item.
 If ListBox1.ListIndex = -1 Then
 ListBox1.ListIndex = _
 ListBox1.ListCount - 1
 End If
 ListBox1.RemoveItem (ListBox1.ListIndex)
 End If
End Sub
Copy code Copy code
Private Sub UserForm_Initialize()
 EntryCount = 0
 CommandButton1.Caption = "Add Item"
 CommandButton2.Caption = "Remove Item"
End Sub


ListBox Control, BoundColumn Property Example

 Copy code hover
[image]

ListBox Control, BoundColumn Property Example
Send feedback

The following example demonstrates how the BoundColumn property influences the value of a ListBox. The user can choose to set the value of the ListBox to the index value of the specified row, or to a specified column of data in the ListBox.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A ListBox named ListBox1.

  • A Label named Label1.

  • Three OptionButton controls named OptionButton1, OptionButton2, and OptionButton3.

Copy code Copy code
Private Sub UserForm_Initialize()
 ListBox1.ColumnCount = 2

 ListBox1.AddItem "Item 1, Column 1"
 ListBox1.List(0, 1) = "Item 1, Column 2"
 ListBox1.AddItem "Item 2, Column 1"
 ListBox1.List(1, 1) = "Item 2, Column 2"

 ListBox1.Value = "Item 1, Column 1"

 OptionButton1.Caption = "List Index"
 OptionButton2.Caption = "Column 1"
 OptionButton3.Caption = "Column 2"
 OptionButton2.Value = True
End Sub

Private Sub OptionButton1_Click()
 ListBox1.BoundColumn = 0
 Label1.Caption = ListBox1.Value
End Sub

Private Sub OptionButton2_Click()
 ListBox1.BoundColumn = 1
 Label1.Caption = ListBox1.Value
End Sub

Private Sub OptionButton3_Click()
 ListBox1.BoundColumn = 2
 Label1.Caption = ListBox1.Value
End Sub

Private Sub ListBox1_Click()
 Label1.Caption = ListBox1.Value
End Sub


ListBox Control, BoundColumn, ControlSource, RowSource Properties Example

 Copy code hover
[image]

ListBox Control, BoundColumn, ControlSource, RowSource Properties Example
Send feedback

The following example uses a range of worksheet cells in a ListBox and, when the user selects a row from the list, displays the row index in another worksheet cell. This code sample uses the RowSource, BoundColumn, and ControlSource properties.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains a ListBox named ListBox1. In the worksheet, enter data in cells A1:E4. You also need to make sure cell A6 contains no data.

Copy code Copy code
Private Sub UserForm_Initialize()

ListBox1.ColumnCount = 5
ListBox1.RowSource = "a1:e4"

ListBox1.ControlSource = "a6"
'Place the ListIndex into cell a6
ListBox1.BoundColumn = 0
End Sub


ListBox Control, Column, ColumnCount, List Properties Example

 Copy code hover
[image]

ListBox Control, Column, ColumnCount, List Properties Example
Send feedback

The following example loads a two-dimensional array with data and, in turn, loads two ListBox controls using the Column and List properties. Note that the Column property transposes the array elements during loading.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains two ListBox controls named ListBox1 and ListBox2.

Copy code Copy code
Dim MyArray(6,3)

Private Sub UserForm_Initialize()
 Dim i As Single
 'The 1st list box contains 3 data columns
 ListBox1.ColumnCount = 3
 'The 2nd box contains 6 data columns
 ListBox2.ColumnCount = 6

 'Load integer values into first column of MyArray
 For i = 0 To 5
 MyArray(i, 0) = i
 Next i

 'Load columns 2 and three of MyArray
 MyArray(0, 1) = "Zero"
 MyArray(1, 1) = "One"
 MyArray(2, 1) = "Two"
 MyArray(3, 1) = "Three"
 MyArray(4, 1) = "Four"
 MyArray(5, 1) = "Five"

 MyArray(0, 2) = "Zero"
 MyArray(1, 2) = "Un ou Une"
 MyArray(2, 2) = "Deux"
 MyArray(3, 2) = "Trois"
 MyArray(4, 2) = "Quatre"
 MyArray(5, 2) = "Cinq"

 'Load data into ListBox1 and ListBox2
 ListBox1.List() = MyArray
 ListBox2.Column() = MyArray

End Sub


ListBox Control, ColumnCount, ColumnWidths Properties Example

 Copy code hover
[image]

ListBox Control, ColumnCount, ColumnWidths Properties Example
Send feedback

The following example uses the ColumnWidths property to change the column widths of a multicolumn ListBox. The example uses three TextBox controls to specify the individual column widths and uses the Exit event to specify the units of measure of each TextBox.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A ListBox named ListBox1.

  • Three TextBox controls named TextBox1 through TextBox3.

  • A CommandButton named CommandButton1.

Try entering the value 0 to hide a column.

Copy code Copy code
Dim MyArray(2, 3) As String

Private Sub CommandButton1_Click()
 'ColumnWidths requires a value for each column
 'separated by semicolons
 ListBox1.ColumnWidths = TextBox1.Text & ";" _
 & TextBox2.Text & ";" & TextBox3.Text
End Sub
Copy code Copy code
Private Sub TextBox1_Exit(ByVal Cancel As _
 MSForms.ReturnBoolean)
 'ColumnWidths accepts points (no units), inches
 'or centimeters; make inches the default
 If Not (InStr(TextBox1.Text, "in") > 0 Or _
 InStr(TextBox1.Text, "cm") > 0) Then
 TextBox1.Text = TextBox1.Text & " in"
 End If
End Sub
Copy code Copy code
Private Sub TextBox2_Exit(ByVal Cancel As _
 MSForms.ReturnBoolean)
 'ColumnWidths accepts points (no units), inches
 'or centimeters; make inches the default
 If Not (InStr(TextBox2.Text, "in") > 0 Or _
 InStr(TextBox2.Text, "cm") > 0) Then
 TextBox2.Text = TextBox2.Text & " in"
 End If
End Sub
Copy code Copy code
Private Sub TextBox3_Exit(ByVal Cancel as MSForms.ReturnBoolean)
 'ColumnWidths accepts points (no units), inches or
 'centimeters; make inches the default
 If Not (InStr(TextBox3.Text, "in") > 0 Or _
 InStr(TextBox3.Text, "cm") > 0) Then
 TextBox3.Text = TextBox3.Text & " in"
 End If
End Sub
Copy code Copy code
Private Sub UserForm_Initialize()
Dim i, j, Rows As Single

ListBox1.ColumnCount = 3
Rows = 2

For j = 0 To ListBox1.ColumnCount - 1
 For i = 0 To Rows - 1
 MyArray(i, j) = "Row " & i & ", Column " & j
 Next i
Next j
'Load MyArray into ListBox1
ListBox1.List() = MyArray
'1-inch columns initially
TextBox1.Text = "1 in"
TextBox2.Text = "1 in"
TextBox3.Text = "1 in"
End Sub


ListBox Control, DataObject Object, MouseMove Event, StartDrag, SetText Methods Example

 Copy code hover
[image]

ListBox Control, DataObject Object, MouseMove Event, StartDrag, SetText Methods Example
Send feedback

The following example demonstrates a drag-and-drop operation from one ListBox to another using a DataObject to contain the dragged text. This code sample uses the SetText and StartDrag methods in the MouseMove event to implement the drag-and-drop operation.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains two ListBox controls named ListBox1 and ListBox2. You also need to add choices to the second ListBox.

Copy code Copy code
Private Sub ListBox2_BeforeDragOver(ByVal Cancel As _
 MSForms.ReturnBoolean, ByVal Data As _
 MSForms.DataObject, ByVal X As Single, _
 ByVal Y As Single, ByVal DragState As Long, _
 ByVal Effect As MSForms.ReturnEffect, _
 ByVal Shift As Integer)
 Cancel = True
 Effect = 1
End Sub

Private Sub ListBox2_BeforeDropOrPaste(ByVal _
 Cancel As MSForms.ReturnBoolean, _
 ByVal Action As Long, ByVal Data As _
 MSForms.DataObject, ByVal X As Single, _
 ByVal Y As Single, ByVal Effect As _
 MSForms.ReturnEffect, ByVal Shift As Integer)
 Cancel = True
 Effect = 1
 ListBox2.AddItem Data.GetText
End Sub

Private Sub ListBox1_MouseMove(ByVal Button As _
 Integer, ByVal Shift As Integer, ByVal X As _
 Single, ByVal Y As Single)
 Dim MyDataObject As DataObject
 If Button = 1 Then
 Set MyDataObject = New DataObject
 Dim Effect As Integer
 MyDataObject.SetText ListBox1.Value
 Effect = MyDataObject.StartDrag
 End If
End Sub

Private Sub UserForm_Initialize()
 For i = 1 To 10
 ListBox1.AddItem "Choice " _
 & (ListBox1.ListCount + 1)
 Next i
End Sub


ListBox Control, List Property Example

 Copy code hover
[image]

ListBox Control, List Property Example
Send feedback

The following example swaps columns of a multicolumn ListBox. The sample uses the List property in two ways:

  1. To access and exchange individual values in the ListBox. In this usage, List has subscripts to designate the row and column of a specified value.

  2. To initially load the ListBox with values from an array. In this usage, List has no subscripts.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains a ListBox named ListBox1 and a CommandButton named CommandButton1.

Copy code Copy code
Dim MyArray(6, 3)
'Array containing column values for ListBox.

Private Sub UserForm_Initialize()
 Dim i As Single

 ListBox1.ColumnCount = 3
'This list box contains 3 data columns

 'Load integer values MyArray
 For i = 0 To 5
 MyArray(i, 0) = i
 MyArray(i, 1) = Rnd
 MyArray(i, 2) = Rnd
 Next i

 'Load ListBox1
 ListBox1.List() = MyArray

End Sub
Copy code Copy code
Private Sub CommandButton1_Click()
' Exchange contents of columns 1 and 3

 Dim i As Single
 Dim Temp As Single

 For i = 0 To 5
 Temp = ListBox1.List(i, 0)
 ListBox1.List(i, 0) = ListBox1.List(i, 2)
 ListBox1.List(i, 2) = Temp
 Next i
End Sub


ListRows Property Example

 Copy code hover
[image]

ListRows Property Example
Send feedback

The following example uses a SpinButton to control the number of rows in the drop-down list of a ComboBox. The user changes the value of the SpinButton, then clicks on the drop-down arrow of the ComboBox to display the list.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A ComboBox named ComboBox1.

  • A SpinButton named SpinButton1.

  • A Label named Label1.

Copy code Copy code
Private Sub UserForm_Initialize()
 Dim i As Integer

 For i = 1 To 20
 ComboBox1.AddItem "Choice " & (ComboBox1.ListCount + 1)
 Next i

 SpinButton1.Min = 0
 SpinButton1.Max = 12
 SpinButton1.Value = ComboBox1.ListRows
 Label1.Caption = "ListRows = " & SpinButton1.Value
End Sub

Private Sub SpinButton1_Change()
 ComboBox1.ListRows = SpinButton1.Value
 Label1.Caption = "ListRows = " & SpinButton1.Value
End Sub


ListStyle, MultiSelect Properties Example

 Copy code hover
[image]

ListStyle, MultiSelect Properties Example
Send feedback

The following example uses the ListStyle and MultiSelect properties to control the appearance of a ListBox. The user chooses a value for ListStyle using the ToggleButton and chooses an OptionButton for one of the MultiSelect values. The appearance of the ListBox changes accordingly, as well as the selection behavior within the ListBox.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A ListBox named ListBox1.

  • A Label named Label1.

  • Three OptionButton controls named OptionButton1 through OptionButton3.

  • A ToggleButton named ToggleButton1.

Copy code Copy code
Private Sub UserForm_Initialize()
 Dim i As Integer

 For i = 1 To 8
 ListBox1.AddItem "Choice" & (ListBox1.ListCount + 1)
 Next i

 Label1.Caption = "MultiSelect Choices"
 Label1.AutoSize = True

 ListBox1.MultiSelect = fmMultiSelectSingle
 OptionButton1.Caption = "Single entry"
 OptionButton1.Value = True
 OptionButton2.Caption = "Multiple entries"
 OptionButton3.Caption = "Extended entries"

 ToggleButton1.Caption = "ListStyle - Plain"
 ToggleButton1.Value = True
 ToggleButton1.Width = 90
 ToggleButton1.Height = 30
End Sub

Private Sub OptionButton1_Click()
 ListBox1.MultiSelect = fmMultiSelectSingle
End Sub

Private Sub OptionButton2_Click()
 ListBox1.MultiSelect = fmMultiSelectMulti
End Sub

Private Sub OptionButton3_Click()
 ListBox1.MultiSelect = fmMultiSelectExtended
End Sub

Private Sub ToggleButton1_Click()
 If ToggleButton1.Value = True Then
 ToggleButton1.Caption = "Plain ListStyle"
 ListBox1.ListStyle = fmListStylePlain
 Else
 ToggleButton1.Caption = "OptionButton " _
 & "or CheckBox"
 ListBox1.ListStyle = fmListStyleOption
 End If
End Sub


ListWidth Property Example

 Copy code hover
[image]

ListWidth Property Example
Send feedback

The following example uses a SpinButton to control the width of the drop-down list of a ComboBox. The user changes the value of the SpinButton, then clicks on the drop-down arrow of the ComboBox to display the list.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A ComboBox named ComboBox1.

  • A SpinButton named SpinButton1.

  • A Label named Label1.

Copy code Copy code
Private Sub SpinButton1_Change()
 ComboBox1.ListWidth = SpinButton1.Value
 Label1.Caption = "ListWidth = " _
 & SpinButton1.Value
End Sub

Private Sub UserForm_Initialize()
 Dim i As Integer

 For i = 1 To 20
 ComboBox1.AddItem "Choice " _
 & (ComboBox1.ListCount + 1)
 Next i

 SpinButton1.Min = 0
 SpinButton1.Max = 130
 SpinButton1.Value = Val(ComboBox1.ListWidth)
 SpinButton1.SmallChange = 5
 Label1.Caption = "ListWidth = " _
 & SpinButton1.Value
End Sub


Locked, DropButtonStyle, ShowDropButtonWhen Properties Example

 Copy code hover
[image]

Locked, DropButtonStyle, ShowDropButtonWhen Properties Example
Send feedback

The following example demonstrates the different symbols that you can specify for a drop-down arrow in a ComboBox or TextBox. In this example, the user chooses a drop-down arrow style from a ComboBox. This example also uses the Locked property. To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A ComboBox named ComboBox1.

  • A Label named Label1.

  • A TextBox named TextBox1 placed beneath Label1.

Copy code Copy code
Private Sub ComboBox1_Click()
 ComboBox1.DropButtonStyle = ComboBox1.Value
 TextBox1.DropButtonStyle = ComboBox1.Value
End Sub

Private Sub UserForm_Initialize()
 ComboBox1.ColumnCount = 2
 ComboBox1.BoundColumn = 2
 ComboBox1.TextColumn = 1

 ComboBox1.AddItem "Blank Button"
 ComboBox1.List(0, 1) = 0
 ComboBox1.AddItem "Down Arrow"
 ComboBox1.List(1, 1) = 1
 ComboBox1.AddItem "Ellipsis"
 ComboBox1.List(2, 1) = 2
 ComboBox1.AddItem "Underscore"
 ComboBox1.List(3, 1) = 3

 ComboBox1.Value = 0

 TextBox1.Text = "TextBox1"
 TextBox1.ShowDropButtonWhen = fmShowDropButtonWhenAlways
 TextBox1.Locked = True

 Label1.Caption = "TheDropButton also " _
 & "applies to a TextBox."
 Label1.AutoSize = True
 Label1.WordWrap = False
End Sub


MatchEntry Property, OptionButton Control Example

 Copy code hover
[image]

MatchEntry Property, OptionButton Control Example
Send feedback

The following example uses the MatchEntry property to demonstrate character matching that is available for ComboBox and ListBox. In this example, the user can set the type of matching with the OptionButton controls and then type into the ComboBox to specify an item from its list.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Three OptionButton controls named OptionButton1 through OptionButton3.

  • A ComboBox named ComboBox1.

Copy code Copy code
Private Sub OptionButton1_Click()
 ComboBox1.MatchEntry = fmMatchEntryNone
End Sub

Private Sub OptionButton2_Click()
 ComboBox1.MatchEntry = fmMatchEntryFirstLetter
End Sub

Private Sub OptionButton3_Click()
 ComboBox1.MatchEntry = fmMatchEntryComplete
End Sub

Private Sub UserForm_Initialize()
 Dim i As Integer

 For i = 1 To 9
 ComboBox1.AddItem "Choice " & i
 Next i
 ComboBox1.AddItem "Chocoholic"

 OptionButton1.Caption = "No matching"
 OptionButton1.Value = True

 OptionButton2.Caption = "Basic matching"
 OptionButton3.Caption = "Extended matching"
End Sub


MatchFound, MatchRequired Properties, Change Event, CheckBox Control Example

 Copy code hover
[image]

MatchFound, MatchRequired Properties, Change Event, CheckBox Control Example
Send feedback

The following example uses the MatchFound and MatchRequired properties to demonstrate additional character matching for ComboBox. The matching verification occurs in the Change event.

In this example, the user specifies whether the text portion of a ComboBox must match one of the listed items in the ComboBox. The user can specify whether matching is required by using a CheckBox and then type into the ComboBox to specify an item from its list.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A ComboBox named ComboBox1.

  • A CheckBox named CheckBox1.

Copy code Copy code
Private Sub CheckBox1_Click()
 If CheckBox1.Value = True Then
 ComboBox1.MatchRequired = True
 MsgBox "To move the focus from the " _
 & "ComboBox, you must match an entry in " _
 & "the list or press ESC."
 Else
 ComboBox1.MatchRequired = False
 MsgBox " To move the focus from the " _
 & "ComboBox, just tab to or click " _
 & "another control. Matching is optional."
 End If
End Sub

Private Sub ComboBox1_Change()
 If ComboBox1.MatchRequired = True Then
 'MSForms handles this case automatically
 Else
 If ComboBox1.MatchFound = True Then
 MsgBox "Match Found; matching optional."
 Else
 MsgBox "Match not Found; matching " _
 & "optional."
 End If
 End If
End Sub

Private Sub UserForm_Initialize()
Dim i As Integer

For i = 1 To 9
 ComboBox1.AddItem "Choice " & i
Next i
ComboBox1.AddItem "Chocoholic"

CheckBox1.Caption = "MatchRequired"
CheckBox1.Value = True
End Sub


Max, Min, MaxLength Properties Example

 Copy code hover
[image]

Max, Min, MaxLength Properties Example
Send feedback

The following example demonstrates the Max and Min properties when used with a stand-alone ScrollBar. The user can set the Max and Min values to any integer in the range of -1000 to 1000. This example also uses the MaxLength property to restrict the number of characters entered for the Max and Min values.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Label named Label1 and a TextBox named TextBox1.

  • A Label named Label2 and a TextBox named TextBox2.

  • A ScrollBar named ScrollBar1.

  • A Label named Label3.

Copy code Copy code
Dim TempNum As Integer

Private Sub UserForm_Initialize()
 Label1.Caption = "Min -1000 to 1000"
 ScrollBar1.Min = -1000
 TextBox1.Text = ScrollBar1.Min
 TextBox1.MaxLength = 5

 Label2.Caption = "Max -1000 to 1000"
 ScrollBar1.Max = 1000
 TextBox2.Text = ScrollBar1.Max
 TextBox2.MaxLength = 5

 ScrollBar1.SmallChange = 1
 ScrollBar1.LargeChange = 100
 ScrollBar1.Value = 0
 Label3.Caption = ScrollBar1.Value
End Sub

Private Sub TextBox1_Change()
 If IsNumeric(TextBox1.Text) Then
 TempNum = CInt(TextBox1.Text)
 If TempNum >= -1000 And TempNum <= 1000 Then
 ScrollBar1.Min = TempNum
 Else
 TextBox1.Text = ScrollBar1.Min
 End If
 Else
 TextBox1.Text = ScrollBar1.Min
 End If
End Sub

Private Sub TextBox2_Change()
 If IsNumeric(TextBox2.Text) Then
 TempNum = CInt(TextBox2.Text)
 If TempNum >= -1000 And TempNum <= 1000 Then
 ScrollBar1.Max = TempNum
 Else
 TextBox2.Text = ScrollBar1.Max
 End If
 Else
 TextBox2.Text = ScrollBar1.Max
 End If
End Sub

Private Sub ScrollBar1_Change()
Label3.Caption = ScrollBar1.Value
End Sub


Max, Min, Zoom Properties, Frame, ScrollBar Controls Example

 Copy code hover
[image]

Max, Min, Zoom Properties, Frame, ScrollBar Controls Example
Send feedback

The following example uses the Zoom property to shrink or enlarge the information displayed on a form, Page, or Frame. This example includes a Frame, a TextBox in the Frame, and a ScrollBar. The magnification level of the Frame changes through Zoom. The user can set Zoom by using the ScrollBar. The TextBox is present to demonstrate the effects of zooming.

This example also uses the Max and Min properties to identify the range of acceptable values for the ScrollBar.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Label named Label1.

  • A ScrollBar named ScrollBar1.

  • A second Label named Label2.

  • A Frame named Frame1.

  • A TextBox named TextBox1 that is located inside Frame1.

Copy code Copy code
Private Sub UserForm_Initialize()
 ScrollBar1.Max = 400
 ScrollBar1.Min = 10
 ScrollBar1.Value = 100

 Label1.Caption = "10 -----Percent of " _
 & "Original Size---- 400"
 Label2.Caption = ScrollBar1.Value

 Frame1.TextBox1.Text = "Enter your text here."
 Frame1.TextBox1.MultiLine = True
 Frame1.TextBox1.WordWrap = True

 Frame1.Zoom = ScrollBar1.Value
End Sub

Private Sub ScrollBar1_Change()
 Frame1.Zoom = ScrollBar1.Value
 Label2.Caption = ScrollBar1.Value
End Sub


MouseIcon, MousePointer Properties Example

 Copy code hover
[image]

MouseIcon, MousePointer Properties Example
Send feedback

The following example demonstrates how to specify a mouse pointer that is appropriate for a specific control or situation. You can assign one of several available mouse pointers using the MousePointer property; or, you can assign a custom icon using the MousePointer and MouseIcon properties.

This example works in the following ways:

  • Choose a mouse pointer from the ListBox to change the mouse pointer associated with the first CommandButton.

  • Click the first CommandButton to associate its mouse pointer with the second CommandButton.

  • Click the second CommandButton to load a custom icon for its mouse pointer.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Two CommandButton controls named CommandButton1 and CommandButton2.

  • A ListBox named ListBox1.

Note Note

This example uses two icon files (identified by the .ico file extention in Windows) that are loaded using the LoadPicture function. You should edit each LoadPicture function call to specify an icon file that resides on your system.
Copy code Copy code
Private Sub ListBox1_Click()
 If IsNull(ListBox1.Value) = False Then
 CommandButton1.MousePointer = ListBox1.Value

 If CommandButton1.MousePointer = _
 fmMousePointerCustom Then
 CommandButton1.MouseIcon = _
 LoadPicture("c:\msvc20\cdk32\" _
 & "samples\circ1\bix.ico")
 End If
 End If
End Sub

Private Sub CommandButton1_Click()
 CommandButton2.MousePointer = CommandButton1.MousePointer

 If CommandButton2.MousePointer = fmMousePointerCustom Then
 CommandButton2.MouseIcon = CommandButton1.MouseIcon
 End If
End Sub

Private Sub CommandButton2_Click()
 CommandButton2.MousePointer = fmMousePointerCustom
 CommandButton2.MouseIcon = LoadPicture("c:\msvc20\cdk32\samples\push\push.ico")
End Sub

Private Sub UserForm_Initialize()
 'Load ListBox with MousePointer choices
 ListBox1.ColumnCount = 2

 ListBox1.AddItem "fmMousePointerDefault"
 ListBox1.List(0, 1) = fmMousePointerDefault
 ListBox1.AddItem "fmMousePointerArrow"
 ListBox1.List(1, 1) = fmMousePointerArrow
 ListBox1.AddItem "fmMousePointerCross"
 ListBox1.List(2, 1) = fmMousePointerCross

 ListBox1.AddItem "fmMousePointerIBeam"
 ListBox1.List(3, 1) = fmMousePointerIBeam
 ListBox1.AddItem "fmMousePointerSizeNESW"
 ListBox1.List(4, 1) = fmMousePointerSizeNESW
 ListBox1.AddItem "fmMousePointerSizeNS"
 ListBox1.List(5, 1) = fmMousePointerSizeNS

 ListBox1.AddItem "fmMousePointerSizeNWSE"
 ListBox1.List(6, 1) = fmMousePointerSizeNWSE
 ListBox1.AddItem "fmMousePointerSizeWE"
 ListBox1.List(7, 1) = fmMousePointerSizeWE
 ListBox1.AddItem "fmMousePointerUpArrow"
 ListBox1.List(8, 1) = fmMousePointerUpArrow

 ListBox1.AddItem "fmMousePointerHourglass"
 ListBox1.List(9, 1) = fmMousePointerHourGlass
 ListBox1.AddItem "fmMousePointerNoDrop"
 ListBox1.List(10, 1) = fmMousePointerNoDrop
 ListBox1.AddItem "fmMousePointerAppStarting"
 ListBox1.List(11, 1) = fmMousePointerAppStarting

 ListBox1.AddItem "fmMousePointerHelp"
 ListBox1.List(12, 1) = fmMousePointerHelp
 ListBox1.AddItem "fmMousePointerSizeAll"
 ListBox1.List(13, 1) = fmMousePointerSizeAll
 ListBox1.AddItem "fmMousePointerCustom"
 ListBox1.List(14, 1) = fmMousePointerCustom

 ListBox1.BoundColumn = 2
 ListBox1.Value = fmMousePointerDefault

 MsgBox "ListBox1.Value =" & ListBox1.Value & "."
 CommandButton1.MousePointer = ListBox1.Value
End Sub


Move Method Example

 Copy code hover
[image]

Move Method Example
Send feedback

The following example demonstrates moving all the controls on a form by using the Move method with the Controls collection. The user clicks on the CommandButton to move the controls.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains a CommandButton named CommandButton1 and several other controls.

Copy code Copy code
Private Sub CommandButton1_Click()
 'Move each control on the form right 25 points
 'and up 25 points.
Controls.Move 25, -25
End Sub


MultiSelect, Selected Properties Example

 Copy code hover
[image]

MultiSelect, Selected Properties Example
Send feedback

The following example uses the MultiSelect and Selected properties to demonstate how the user can select one or more items in a ListBox. The user specifies a selection method by choosing an option button and then selects an item(s) from the ListBox. The user can display the selected items in a second ListBox by clicking the CommandButton.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Two ListBox controls named ListBox1 and ListBox2.

  • A CommandButton named CommandButton1.

  • Three OptionButton controls named OptionButton1 through OptionButton3.

Copy code Copy code
Dim i As Integer

Private Sub CommandButton1_Click()
 ListBox2.Clear

 For i = 0 To 9
 If ListBox1.Selected(i) = True Then
 ListBox2.AddItem ListBox1.List(i)
 End If
 Next i

End Sub

Private Sub OptionButton1_Click()
 ListBox1.MultiSelect = fmMultiSelectSingle
End Sub

Private Sub OptionButton2_Click()
 ListBox1.MultiSelect = fmMultiSelectMulti
End Sub

Private Sub OptionButton3_Click()
 ListBox1.MultiSelect = fmMultiSelectExtended
End Sub

Private Sub UserForm_Initialize()
 For i = 0 To 9
 ListBox1.AddItem "Choice " & (ListBox1.ListCount + 1)
 Next i

 OptionButton1.Caption = "Single Selection"
 ListBox1.MultiSelect = fmMultiSelectSingle
 OptionButton1.Value = True

 OptionButton2.Caption = "Multiple Selection"
 OptionButton3.Caption = "Extended Selection"

 CommandButton1.Caption = "Show selections"
 CommandButton1.AutoSize = True
End Sub


Name Property Example

 Copy code hover
[image]

Name Property Example
Send feedback

The following example displays the Name property of each control on a form. This example uses the Controls collection to cycle through all the controls placed directly on the Userform.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains a CommandButton named CommandButton1 and several other controls.

Copy code Copy code
Private Sub CommandButton1_Click()
 Dim MyControl As Control

 For Each MyControl In Controls
 MsgBox "MyControl.Name = " & MyControl.Name
 Next
End Sub


Object Property Example

 Copy code hover
[image]

Object Property Example
Send feedback

Assume a new control has a Top property that is different from the standard Top property in Microsoft Forms. You can use either property, based on the syntax:

  • control.Top uses the standard Top property.

  • control.Object.Top uses the Top property from the added control.


Page Object, CommandButton, MultiPage Controls, ControlTipText Property Example

 Copy code hover
[image]

Page Object, CommandButton, MultiPage Controls, ControlTipText Property Example
Send feedback

The following example defines the ControlTipText property for three CommandButton controls and two Page objects in a MultiPage.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A MultiPage named MultiPage1.

  • Three CommandButton controls named CommandButton1 through CommandButton3.

Note Note

For an individual Page of a MultiPage, ControlTipText becomes enabled when the MultiPage or a control on the current page of the MultiPage has the focus.
Copy code Copy code
Private Sub UserForm_Initialize()
 MultiPage1.Page1.ControlTipText = "Here in page 1"
 MultiPage1.Page2.ControlTipText = "Now in page 2"

 CommandButton1.ControlTipText = "And now here's"
 CommandButton2.ControlTipText = "a tip from"
 CommandButton3.ControlTipText = "your controls!"
End Sub


Page Object, MultiPage Control, Add, Clear, Remove Methods Example

 Copy code hover
[image]

Page Object, MultiPage Control, Add, Clear, Remove Methods Example
Send feedback

The following example uses the Add, Clear, and Remove methods to add and remove a control to a Page of a MultiPage at run time.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A MultiPage named MultiPage1.

  • Three CommandButton controls named CommandButton1 through CommandButton3.

Copy code Copy code
Dim MyTextBox As Control

Private Sub CommandButton1_Click()
Set MyTextBox = MultiPage1.Pages(0).Controls.Add("MSForms" _
 & ".TextBox.1", "MyTextBox", Visible)
End Sub

Private Sub CommandButton2_Click()
 MultiPage1.Pages(0).Controls.Clear
End Sub

Private Sub CommandButton3_Click()
 If MultiPage1.Pages(0).Controls.Count > 0 Then
 MultiPage1.Pages(0).Controls.Remove "MyTextBox"
 End If
End Sub

Private Sub UserForm_Initialize()
 CommandButton1.Caption = "Add control"
 CommandButton2.Caption = "Clear controls"
 CommandButton3.Caption = "Remove control"
End Sub


Page Object, Pages Collection, MultiPage Control, SelectedItem Property Example

 Copy code hover
[image]

Page Object, Pages Collection, MultiPage Control, SelectedItem Property Example
Send feedback

The following example accesses an individual page of a MultiPage in several ways:

  • Using the Pages collection with a numeric index.

  • Using the Pages collection with a string index.

  • Using the Pages collection with the Item method.

  • Using the name of the individual page in the MultiPage.

  • Using the SelectedItem property.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains a MultiPage named MultiPage1.

Copy code Copy code
Private Sub UserForm_Initialize()
 Dim PageName As String

 For i = 0 To MultiPage1.Count - 1
 'Use index (numeric or string)
 MsgBox "MultiPage1.Pages(i).Caption = " _
 & MultiPage1.Pages(i).Caption
 MsgBox "MultiPage1.Pages.Item(i).Caption = " _
 & MultiPage1.Pages.Item(i).Caption

 PageName = MultiPage1.Pages(i).Name
 MsgBox "PageName = " & PageName

 MsgBox "MultiPage1.Pages(PageName)" _
 & ".Caption = "_
 & MultiPage1.Pages(PageName).Caption
 MsgBox "MultiPage1.Pages.Item(PageName)" _
 & ".Caption = " & MultiPage1.Pages _
 .Item(PageName).Caption

 'Use Page object without referring to
 'Pages collection
 If i = 0 Then
 MsgBox "MultiPage1.Page1.Caption= " _
 & MultiPage1.Page1.Caption
 ElseIf i = 1 Then
 MsgBox "MultiPage1.Page2.Caption = " _
 & MultiPage1.Page2.Caption
 End If

 'Use SelectedItem Property
 MultiPage1.Value = i
 MsgBox "MultiPage1.SelectedItem.Caption = " _
 & MultiPage1.SelectedItem.Caption
 Next i
End Sub


Parent Property Example

 Copy code hover
[image]

Parent Property Example
Send feedback

The following example uses the Parent property to refer to the control or form that contains a specific control.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Two Label controls named Label1 and Label2.

  • A CommandButton named CommandButton1.

  • One or more additional controls of your choice.

Copy code Copy code
Dim MyControl As Object
Dim MyParent As Object
Dim ControlsIndex As Integer

Private Sub UserForm_Initialize()
 ControlsIndex = 0
 CommandButton1.Caption = "Get Control and Parent"
 CommandButton1.AutoSize = True
 CommandButton1.WordWrap = True
End Sub

Private Sub CommandButton1_Click()
 'Process Controls collection for UserForm
 Set MyControl = Controls.Item(ControlsIndex)
 Set MyParent = MyControl.Parent
 Label1.Caption = MyControl.Name
 Label2.Caption = MyParent.Name

 'Prepare index for next control on Userform
 ControlsIndex = ControlsIndex + 1
 If ControlsIndex >= Controls.Count Then
 ControlsIndex = 0
 End If
End Sub


Paste, PutInClipboard, SetText Methods Example

 Copy code hover
[image]

Paste, PutInClipboard, SetText Methods Example
Send feedback

The following example demonstrates data movement from a TextBox to a DataObject, from a DataObject to the Clipboard, and from the Clipboard to another TextBox. The PutInClipboard method transfers the data from a DataObject to the Clipboard. The SetText and Paste methods are also used.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Two TextBox controls named TextBox1 and TextBox2.

  • A CommandButton named CommandButton1.

Copy code Copy code
Dim MyData As DataObject

Private Sub CommandButton1_Click()
 Set MyData = New DataObject

 MyData.SetText TextBox1.Text
 MyData.PutInClipboard

 TextBox2.Paste
End Sub

Private Sub UserForm_Initialize()
 TextBox1.Text = "Move this data to a " _
 & "DataObject, to the Clipboard, then to " _
 & "TextBox2!"
End Sub


PictureAlignment Property Example

 Copy code hover
[image]

PictureAlignment Property Example
Send feedback

The following example uses the PictureAlignment property to set up a background picture. The example also identifies the alignment options provided by PictureAlignment.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Frame named Frame1.

  • A SpinButton named SpinButton1.

  • A TextBox named TextBox1.

Copy code Copy code
Dim Alignments(5) As String

Private Sub UserForm_Initialize()
 Alignments(0) = "0 - Top Left"
 Alignments(1) = "1 - Top Right"
 Alignments(2) = "2 - Center"
 Alignments(3) = "3 - Bottom Left"
 Alignments(4) = "4 - Bottom Right"

 'Specify a bitmap that exists on your system
 Frame1.Picture = LoadPicture("c:\winnt2\ball.bmp")

 SpinButton1.Min = 0
 SpinButton1.Max = 4
 SpinButton1.Value = 0

 TextBox1.Text = Alignments(0)
 Frame1.PictureAlignment = SpinButton1.Value
End Sub

Private Sub SpinButton1_Change()
 TextBox1.Text = Alignments(SpinButton1.Value)
 Frame1.PictureAlignment = SpinButton1.Value
End Sub

Private Sub TextBox1_Change()
 Select Case TextBox1.Text
 Case "0"
 TextBox1.Text = Alignments(0)
 Frame1.PictureAlignment = 0
 Case "1"
 TextBox1.Text = Alignments(1)
 Frame1.PictureAlignment = 1
 Case "2"
 TextBox1.Text = Alignments(2)
 Frame1.PictureAlignment = 2
 Case "3"
 TextBox1.Text = Alignments(3)
 Frame1.PictureAlignment = 3
 Case "4"
 TextBox1.Text = Alignments(4)
 Frame1.PictureAlignment = 4
 Case Else
 TextBox1.Text = Alignments(SpinButton1.Value)
 Frame1.PictureAlignment = SpinButton1.Value
 End Select
End Sub


PictureSizeMode Property Example

 Copy code hover
[image]

PictureSizeMode Property Example
Send feedback

The following example uses the PictureSizeMode property to demonstrate three display options for a picture: showing the picture as is, changing the size of the picture while maintaining its original proportions, and stretching the picture to fill a space.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Frame named Frame1.

  • A SpinButton named SpinButton1.

  • A TextBox named TextBox1.

  • Three OptionButton controls named OptionButton1 through OptionButton3.

Note Note

This example is an enhanced version of the PictureAlignment property example, as the two properties complement each other. The enhancements are three OptionButton event subroutines that control whether the image is cropped, zoomed, or stretched.
Copy code Copy code
Dim Alignments(5) As String

Private Sub UserForm_Initialize()
 Alignments(0) = "0 - Top Left"
 Alignments(1) = "1 - Top Right"
 Alignments(2) = "2 - Center"
 Alignments(3) = "3 - Bottom Left"
 Alignments(4) = "4 - Bottom Right"

 'Specify a bitmap that exists on your system
 Frame1.Picture = LoadPicture("c:\winnt2\ball.bmp")

 SpinButton1.Min = 0
 SpinButton1.Max = 4
 SpinButton1.Value = 0

 TextBox1.Text = Alignments(0)
 Frame1.PictureAlignment = SpinButton1.Value

 OptionButton1.Caption = "Crop"
 OptionButton1.Value = True
 OptionButton2.Caption = "Stretch"
 OptionButton3.Caption = "Zoom"
End Sub

Private Sub OptionButton1_Click()
 If OptionButton1.Value = True Then
 Frame1.PictureSizeMode = fmPictureSizeModeClip
 End If
End Sub

Private Sub OptionButton2_Click()
 If OptionButton2.Value = True Then
 Frame1.PictureSizeMode = fmPictureSizeModeStretch
 End If
End Sub

Private Sub OptionButton3_Click()
 If OptionButton3.Value = True Then
 Frame1.PictureSizeMode = fmPictureSizeModeZoom
 End If
End Sub

Private Sub SpinButton1_Change()
 TextBox1.Text = Alignments(SpinButton1.Value)
 Frame1.PictureAlignment = SpinButton1.Value
End Sub

Private Sub TextBox1_Change()
 Select Case TextBox1.Text
 Case "0"
 TextBox1.Text = Alignments(0)
 Frame1.PictureAlignment = 0
 Case "1"
 TextBox1.Text = Alignments(1)
 Frame1.PictureAlignment = 1
 Case "2"
 TextBox1.Text = Alignments(2)
 Frame1.PictureAlignment = 2
 Case "3"
 TextBox1.Text = Alignments(3)
 Frame1.PictureAlignment = 3
 Case "4"
 TextBox1.Text = Alignments(4)
 Frame1.PictureAlignment = 4
 Case Else
 TextBox1.Text = Alignments(SpinButton1.Value)
 Frame1.PictureAlignment = SpinButton1.Value
 End Select
End Sub


ScrollBar Control, Scroll Event Example

 Copy code hover
[image]

ScrollBar Control, Scroll Event Example
Send feedback

The following example demonstrates the stand-alone ScrollBar and reports the change in its value as the user moves the scroll box. The user can move the scroll box by clicking on either arrow at the ends of the control, by clicking in the region between scroll box and either arrow, or by dragging the scroll box. When the user drags the scroll box, the Scroll event displays a message indicating that the user scrolled to obtain the new value.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A ScrollBar named ScrollBar1.

  • Two Label controls named Label1 and Label2. Label1 contains scaling information for the user. Label2 reports the delta value.

Copy code Copy code
Dim ScrollSaved As Integer
'Previous ScrollBar setting

Private Sub UserForm_Initialize()
 ScrollBar1.Min = -225
 ScrollBar1.Max = 289
 ScrollBar1.Value = 0

 Label1.Caption = "-225 -----Widgets----- 289"
 Label1.AutoSize = True

 Label2.Caption = ""
End Sub

Private Sub ScrollBar1_Change()
 Label2.Caption = " Widget Changes " _
 & (ScrollSaved - ScrollBar1.Value)
End Sub

Private Sub ScrollBar1_Exit(ByVal Cancel as MSForms.ReturnBoolean)
 Label2.Caption = " Widget Changes " _
 & (ScrollSaved - ScrollBar1.Value)
 ScrollSaved = ScrollBar1.Value
End Sub

Private Sub ScrollBar1_Scroll()
 Label2.Caption = (ScrollSaved - ScrollBar1 _
 .Value) & " Widget Changes by Scrolling"
End Sub


ScrollBars, KeepScrollBarsVisible Properties Example

 Copy code hover
[image]

ScrollBars, KeepScrollBarsVisible Properties Example
Send feedback

The following example uses the ScrollBars and the KeepScrollBarsVisible properties to add scroll bars to a page of a MultiPage and to a Frame. The user chooses an option button that, in turn, specifies a value for KeepScrollBarsVisible.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A MultiPage named MultiPage1.

  • A Frame named Frame1.

  • Four OptionButton controls named OptionButton1 through OptionButton4.

Copy code Copy code
Private Sub UserForm_Initialize()
 MultiPage1.Pages(0).ScrollBars = fmScrollBarsBoth
 MultiPage1.Pages(0).KeepScrollBarsVisible = fmScrollBarsNone

 Frame1.ScrollBars = fmScrollBarsBoth
 Frame1.KeepScrollBarsVisible = fmScrollBarsNone

 OptionButton1.Caption = "No scroll bars"
 OptionButton1.Value = True
 OptionButton2.Caption = "Horizontal scroll bars"
 OptionButton3.Caption = "Vertical scroll bars"
 OptionButton4.Caption = "Both scroll bars"
End Sub

Private Sub OptionButton1_Click()
 MultiPage1.Pages(0).KeepScrollBarsVisible = _
 fmScrollBarsNone
 Frame1.KeepScrollBarsVisible = fmScrollBarsNone
End Sub

Private Sub OptionButton2_Click()
 MultiPage1.Pages(0).KeepScrollBarsVisible = _
 fmScrollBarsHorizontal
 Frame1.KeepScrollBarsVisible = _
 fmScrollBarsHorizontal
End Sub

Private Sub OptionButton3_Click()
 MultiPage1.Pages(0).KeepScrollBarsVisible = _
 fmScrollBarsVertical
 Frame1.KeepScrollBarsVisible = _
 fmScrollBarsVertical
End Sub

Private Sub OptionButton4_Click()
 MultiPage1.Pages(0).KeepScrollBarsVisible = _
 fmScrollBarsBoth
 Frame1.KeepScrollBarsVisible = fmScrollBarsBoth
End Sub


ScrollHeight, ScrollLeft, ScrollTop, ScrollWidth Properties Example

 Copy code hover
[image]

ScrollHeight, ScrollLeft, ScrollTop, ScrollWidth Properties Example
Send feedback

The following example uses a page of a MultiPage as a scrolling region. The user can use the scroll bars on Page2 of the MultiPage to gain access to parts of the page that are not initially displayed.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains a MultiPage named MultiPage1, and that each page of the MultiPage contains one or more controls.

Note Note

Each page of a MultiPage is unique. Page1 has no scroll bars. Page2 has horizontal and vertical scroll bars.
Copy code Copy code
Private Sub UserForm_Initialize()
 MultiPage1.Pages(1).ScrollBars = fmScrollBarsBoth
 MultiPage1.Pages(1).KeepScrollBarsVisible = _
 fmScrollBarsNone

 MultiPage1.Pages(1).ScrollHeight = 2 * _
 MultiPage1.Height
 MultiPage1.Pages(1).ScrollWidth = 2 * _
 MultiPage1.Width

 'Set ScrollHeight, ScrollWidth before setting
 'ScrollLeft, ScrollTop
 MultiPage1.Pages(1).ScrollLeft = _
 MultiPage1.Width / 2
 MultiPage1.Pages(1).ScrollTop = _
 MultiPage1.Height / 2
End Sub


SelectedItem Property, TabStrip Control, Tab Object, Tabs Collection Example

 Copy code hover
[image]

SelectedItem Property, TabStrip Control, Tab Object, Tabs Collection Example
Send feedback

The following example accesses an individual tab of a TabStrip in several ways:

  • Using the Tabs collection with a numeric index.

  • Using the Tabs collection with a string index.

  • Using the Tabs collection with the Item method.

  • Using the name of the individual Tab.

  • Using the SelectedItem property.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains a TabStrip named TabStrip1.

Copy code Copy code
Private Sub UserForm_Initialize()
 Dim TabName As String

 For i = 0 To TabStrip1.Count - 1
 'Using index (numeric or string)
 MsgBox "TabStrip1.Tabs(i).Caption = " _
 & TabStrip1.Tabs(i).Caption
 MsgBox "TabStrip1.Tabs.Item(i).Caption = " _
 & TabStrip1.Tabs.Item(i).Caption

 TabName = TabStrip1.Tabs(i).Name
 MsgBox "TabName = " & TabName

 MsgBox "TabStrip1.Tabs(TabName).Caption = " _
 & TabStrip1.Tabs(TabName).Caption
 MsgBox "TabStrip1.Tabs.Item(TabName)_
 .Caption = " _
 & TabStrip1.Tabs.Item(TabName).Caption

 'Use Tab object without referring to Tabs
 'collection
 If i = 0 Then
 MsgBox "TabStrip1.Tab1.Caption = " _
 & TabStrip1.Tab1.Caption
 ElseIf i = 1 Then
 MsgBox "TabStrip1.Tab2.Caption = " _
 & TabStrip1.Tab2.Caption
 EndIf

 'Use SelectedItem Property
 TabStrip1.Value = i
 MsgBox "TabStrip1.SelectedItem.Caption = " _
 & TabStrip1.SelectedItem.Caption
 Next i
End Sub


SetFocus Method, LineCount, TextLength Properties Example

 Copy code hover
[image]

SetFocus Method, LineCount, TextLength Properties Example
Send feedback

The following example counts the characters and the number of lines of text in a TextBox by using the LineCount and TextLength properties, and the SetFocus method. In this example, the user can type into a TextBox, and can retrieve current values of the LineCount and TextLength properties.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains the following controls:

  • A TextBox named TextBox1.

  • A CommandButton named CommandButton1.

  • Two Label controls named Label1 and Label2.

Copy code Copy code
'Type SHIFT+ENTER to start a new line in the text box.

Private Sub CommandButton1_Click()
 'Must first give TextBox1 the focus to get line
 'count
 TextBox1.SetFocus
 Label1.Caption = "LineCount = " _
 & TextBox1.LineCount
 Label2.Caption = "TextLength = " _
 & TextBox1.TextLength
End Sub

Private Sub UserForm_Initialize()
 CommandButton1.WordWrap = True
 CommandButton1.AutoSize = True
 CommandButton1.Caption = "Get Counts"

 Label1.Caption = "LineCount = "
 Label2.Caption = "TextLength = "

 TextBox1.MultiLine = True
 TextBox1.WordWrap = True
 TextBox1.Text = "Enter your text here."
End Sub


SpinDown, SpinUp Events, Delay Property Example

 Copy code hover
[image]

SpinDown, SpinUp Events, Delay Property Example
Send feedback

The following example demonstrates the time interval between successive Change, SpinUp, and SpinDown events that occur when a user holds down the mouse button to change the value of a SpinButton or ScrollBar.

In this example, the user chooses a delay setting, then clicks and holds down either side of a SpinButton. The SpinUp and SpinDown events are recorded in a ListBox as they are initiated.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A SpinButton named SpinButton1.

  • Two OptionButton controls named OptionButton1 and OptionButton2.

  • A ListBox named ListBox1.

Copy code Copy code
Dim EventCount As Long

Private Sub ResetControl()
 ListBox1.Clear
 EventCount = 0
 SpinButton1.Value = 5000
End Sub

Private Sub UserForm_Initialize()
 SpinButton1.Min = 0
 SpinButton1.Max = 10000
 ResetControl

 SpinButton1.Delay = 50
 OptionButton1.Caption = "50 millisecond delay"
 OptionButton2.Caption = "250 millisecond delay"

 OptionButton1.Value = True
End Sub

Private Sub OptionButton1_Click()
 SpinButton1.Delay = 50
 ResetControl
End Sub

Private Sub OptionButton2_Click()
 SpinButton1.Delay = 250
 ResetControl
End Sub

Private Sub SpinButton1_SpinDown()
 EventCount = EventCount + 1
 ListBox1.AddItem EventCount
End Sub

Private Sub SpinButton1_SpinUp()
 EventCount = EventCount + 1
 ListBox1.AddItem EventCount
End Sub


Style Property Example

 Copy code hover
[image]

Style Property Example
Send feedback

The following example uses the Style property to change the effect of typing in the text area of a ComboBox. The user chooses a style by selecting an OptionButton control and then types into the ComboBox to select an item. When Style is fmStyleDropDownList, the user must choose an item from the drop-down list. When Style is fmStyleDropDownCombo, the user can type into the text area to specify an item in the drop-down list.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Two OptionButton controls named OptionButton1 and OptionButton2.

  • A ComboBox named ComboBox1.

Copy code Copy code
Private Sub OptionButton1_Click()
 ComboBox1.Style = fmStyleDropDownCombo
End Sub

Private Sub OptionButton2_Click()
 ComboBox1.Style = fmStyleDropDownList
End Sub

Private Sub UserForm_Initialize()
 Dim i As Integer

 For i = 1 To 10
 ComboBox1.AddItem "Choice " & i
 Next i

 OptionButton1.Caption = "Select like ComboBox"
 OptionButton1.Value = True
 ComboBox1.Style = fmStyleDropDownCombo

 OptionButton2.Caption = "Select like ListBox"
End Sub


Style Property, Label Control Example

 Copy code hover
[image]

Style Property, Label Control Example
Send feedback

The following example uses the Style property to specify the appearance of the tabs in MultiPage and TabStrip. This example also demonstrates using a Label. The user chooses a style by selecting an OptionButton.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Label named Label1.

  • Three OptionButton controls named OptionButton1 through OptionButton3.

  • A MultiPage named MultiPage1.

  • A TabStrip named TabStrip1.

  • Any control inside the TabStrip.

  • Any control in each page of the MultiPage.

Copy code Copy code
Private Sub OptionButton1_Click()
 MultiPage1.Style = fmTabStyleTabs
 TabStrip1.Style = fmTabStyleTabs
End Sub

Private Sub OptionButton2_Click()
 'Note that the page borders are invisible
 MultiPage1.Style = fmTabStyleButtons
 TabStrip1.Style = fmTabStyleButtons
End Sub

Private Sub OptionButton3_Click()
 'Note that the page borders are invisible and
 'the page body begins where the tabs normally
 'appear.
 MultiPage1.Style = fmTabStyleNone
 TabStrip1.Style = fmTabStyleNone
End Sub

Private Sub UserForm_Initialize()
 Label1.Caption = "Page/Tab Style"
 OptionButton1.Caption = "Tabs"
 OptionButton1.Value = True
 MultiPage1.Style = fmTabStyleTabs
 TabStrip1.Style = fmTabStyleTabs

 OptionButton2.Caption = "Buttons"
 OptionButton3.Caption = "No Tabs or Buttons"
End Sub


TabFixedHeight, TabFixedWidth Properties Example

 Copy code hover
[image]

TabFixedHeight, TabFixedWidth Properties Example
Send feedback

The following example uses the TabFixedHeight and TabFixedWidth properties to set the size of the tabs used in MultiPage and TabStrip. The user clicks the SpinButton controls to adjust the height and width of the tabs within the MultiPage and TabStrip.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A MultiPage named MultiPage1.

  • A TabStrip named TabStrip1.

  • A Label named Label1 for the width control.

  • A SpinButton named SpinButton1 for the width control.

  • A TextBox named TextBox1 for the width control.

  • A Label named Label2 for the height control.

  • A SpinButton named SpinButton2 for the height control.

  • A TextBox named TextBox2 for the height control.

Copy code Copy code
Private Sub UpdateTabWidth()
 TextBox1.Text = SpinButton1.Value
 TabStrip1.TabFixedWidth = SpinButton1.Value
 MultiPage1.TabFixedWidth = SpinButton1.Value
End Sub

Private Sub UpdateTabHeight()
 TextBox2.Text = SpinButton2.Value
 TabStrip1.TabFixedHeight = SpinButton2.Value
 MultiPage1.TabFixedHeight = SpinButton2.Value
End Sub

Private Sub UserForm_Initialize()
 MultiPage1.Style = fmTabStyleButtons

 Label1.Caption = "Tab Width"
 SpinButton1.Min = 0
 SpinButton1.Max = _
 TabStrip1.Width / TabStrip1.Tabs.Count
 SpinButton1.Value = 0
 TextBox1.Locked = True

 UpdateTabWidth

 Label2.Caption = "Tab Height"
 SpinButton2.Min = 0
 SpinButton2.Max = TabStrip1.Height
 SpinButton2.Value = 0
 TextBox2.Locked = True

 UpdateTabHeight
End Sub

Private Sub SpinButton1_SpinDown()
 UpdateTabWidth
End Sub

Private Sub SpinButton1_SpinUp()
 UpdateTabWidth
End Sub

Private Sub SpinButton2_SpinDown()
 UpdateTabHeight
End Sub

Private Sub SpinButton2_SpinUp()
 UpdateTabHeight
End Sub


TabIndex Property Example

 Copy code hover
[image]

TabIndex Property Example
Send feedback

The following example uses the TabIndex property to display and set the tab order for individual controls. The user can press TAB to reach the next control in the tab order and to display the TabIndex of that control. The user can also click on a control to display its TabIndex. The User can change the TabIndex of a control by specifying a new index value in the TextBox and clicking CommandButton3. Changing the TabIndex for one control also updates the TabIndex for other controls in the Frame.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Label named Label1.

  • A TextBox named TextBox1.

  • A Frame named Frame1.

  • A TextBox in the Frame named TextBox2.

  • Two CommandButton controls in the Frame named CommandButton1 and CommandButton2.

  • A ScrollBar in the Frame named ScrollBar1.

  • A CommandButton (not in the Frame) named CommandButton3.

Copy code Copy code
Private Sub MoveToFront()
 Dim i, Temp As Integer

 Temp = Frame1.ActiveControl.TabIndex
 For i = 0 To Temp - 1
 Frame1.Controls.Item(i).TabIndex = i + 1
 Next i

 Frame1.ActiveControl.TabIndex = 0
 TextBox1.Text = Frame1.ActiveControl.TabIndex
End Sub

Private Sub CommandButton3_Click()
 Dim i, Temp As Integer

 If IsNumeric(TextBox1.Text) Then
 Temp = Val(TextBox1.Text)

 If Temp >= Frame1.Controls.Count Or Temp < 0
 Then
 'Entry out of range; move control to front
 'of tab order
 MoveToFront
 ElseIf
 Temp > Frame1.ActiveControl.TabIndex
 Then
 'Move entry down the list
 For i = Frame1.ActiveControl.TabIndex + _
 1 To Temp
 Frame1.Controls.Item(i).TabIndex = _
 i - 1
 Next i
 Frame1.ActiveControl.TabIndex = Temp
 TextBox1.Text = _
 Frame1.ActiveControl.TabIndex
 Else
 'Move Entry up the list
 For i = Frame1.ActiveControl.TabIndex - _
 1 To Temp
 Frame1.Controls.Item(i).TabIndex = _
 i + 1
 Next i
 Frame1.ActiveControl.TabIndex = Temp
 TextBox1.Text = _
 Frame1.ActiveControl.TabIndex
 End If
 Else
 'Text entry; move control to front of tab
 'order
 MoveToFront
 End If
End Sub

Private Sub UserForm_Initialize()
 Label1.Caption = "TabIndex"

 Frame1.Controls(0).SetFocus
 TextBox1.Text = Frame1.ActiveControl.TabIndex

 Frame1.Cycle = fmCycleCurrentForm

 CommandButton3.Caption = "Set TabIndex"
 CommandButton3.TakeFocusOnClick = False
End Sub

Private Sub TextBox2_Enter()
 TextBox1.Text = Frame1.ActiveControl.TabIndex
End Sub

Private Sub CommandButton1_Enter()
 TextBox1.Text = Frame1.ActiveControl.TabIndex
End Sub

Private Sub CommandButton2_Enter()
 TextBox1.Text = Frame1.ActiveControl.TabIndex
End Sub

Private Sub ScrollBar1_Enter()
 TextBox1.Text = Frame1.ActiveControl.TabIndex
End Sub


TabStop Property Example

 Copy code hover
[image]

TabStop Property Example
Send feedback

The following example uses the TabStop property to control whether a user can press TAB to move the focus to a particular control. The user presses TAB to move the focus among the controls on the form, and then clicks the ToggleButton to change TabStop for CommandButton1. When TabStop is False, CommandButton1 will not receive the focus by using TAB.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A CommandButton named CommandButton1.

  • A ToggleButton named ToggleButton1.

  • One or two other controls, such as an OptionButton or ListBox.

Copy code Copy code
Private Sub CommandButton1_Click()
 MsgBox "Clicked CommandButton1."
End Sub

Private Sub ToggleButton1_Click()
 If ToggleButton1 = True Then
 CommandButton1.TabStop = True
 ToggleButton1.Caption = "TabStop On"
 Else
 CommandButton1.TabStop = False
 ToggleButton1.Caption = "TabStop Off"
 End If
End Sub

Private Sub UserForm_Initialize()
 CommandButton1.Caption = "Show Message"

 ToggleButton1.Caption = "TabStop On"
 ToggleButton1.Value = True
 ToggleButton1.Width = 90
End Sub


Tag Property Example

 Copy code hover
[image]

Tag Property Example
Send feedback

The following example uses the Tag property to store additional information about each control on the UserForm. The user clicks a control and then clicks the CommandButton. The contents of Tag for the appropriate control are returned in the TextBox.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A TextBox named TextBox1.

  • A CommandButton named CommandButton1.

  • A ScrollBar named ScrollBar1.

  • A ComboBox named ComboBox1.

  • A MultiPage named MultiPage1.

Copy code Copy code
Private Sub CommandButton1_Click()
 TextBox1.Text = ActiveControl.Tag
End Sub

Private Sub UserForm_Initialize()
 TextBox1.Locked = True
 TextBox1.Tag = "Display area for Tag properties."
 TextBox1.AutoSize = True

 CommandButton1.Caption = "Show Tag of Current " _
 & "Control."
 CommandButton1.AutoSize = True
 CommandButton1.WordWrap = True
 CommandButton1.TakeFocusOnClick = False
 CommandButton1.Tag = "Shows tag of control " _
 & "that has the focus."

 ComboBox1.Style = fmStyleDropDownList
 ComboBox1.Tag = "ComboBox Style is that of " _
 & "a ListBox."

 ScrollBar1.Max = 100
 ScrollBar1.Min = -273
 ScrollBar1.Tag = "Max = " & ScrollBar1.Max _
 & " , Min = " & ScrollBar1.Min

 MultiPage1.Pages.Add
 MultiPage1.Pages.Add
 MultiPage1.Tag = "This MultiPage has " _
 & MultiPage1.Pages.Count & " pages."
End Sub


TakeFocusOnClick Property Example

 Copy code hover
[image]

TakeFocusOnClick Property Example
Send feedback

The following example uses the TakeFocusOnClick property to control whether a CommandButton receives the focus when the user clicks on it. The user clicks a control other than CommandButton1 and then clicks CommandButton1. If TakeFocusOnClick is True, CommandButton1 receives the focus after it is clicked. The user can change the value of TakeFocusOnClick by clicking the ToggleButton.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A CommandButton named CommandButton1.

  • A ToggleButton named ToggleButton1.

  • One or two other controls, such as an OptionButton or ListBox.

Copy code Copy code
Private Sub CommandButton1_Click()
 MsgBox "Watch CommandButton1 to see if it " _
 & "takes the focus."
End Sub

Private Sub ToggleButton1_Click()
 If ToggleButton1 = True Then
 CommandButton1.TakeFocusOnClick = True
 ToggleButton1.Caption = "TakeFocusOnClick On"
 Else
 CommandButton1.TakeFocusOnClick = False
 ToggleButton1.Caption = "TakeFocusOnClick Off"
 End If
End Sub

Private Sub UserForm_Initialize()
 CommandButton1.Caption = "Show Message"

 ToggleButton1.Caption = "TakeFocusOnClick On"
 ToggleButton1.Value = True
 ToggleButton1.Width = 90
End Sub


TextBox Control, AutoSize, Text Properties Example

 Copy code hover
[image]

TextBox Control, AutoSize, Text Properties Example
Send feedback

The following example demonstrates the effects of the AutoSize property with a single-line TextBox and a multiline TextBox. The user can enter text into either TextBox and turn AutoSize on or off independently of the contents of the TextBox. This code sample also uses the Text property.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Two TextBox controls named TextBox1 and TextBox2.

  • A ToggleButton named ToggleButton1.

Copy code Copy code
Private Sub UserForm_Initialize()
 TextBox1.Text = "Single-line TextBox. " _
 & "Type your text here."

 TextBox2.MultiLine = True
 TextBox2.Text = "Multi-line TextBox. Type " _
 & "your text here. Use CTRL+ENTER to start " _
 & "a new line."

 ToggleButton1.Value = True
 ToggleButton1.Caption = "AutoSize On"
 TextBox1.AutoSize = True
 TextBox2.AutoSize = True
End Sub

Private Sub ToggleButton1_Click()
 If ToggleButton1.Value = True Then
 ToggleButton1.Caption = "AutoSize On"
 TextBox1.AutoSize = True
 TextBox2.AutoSize = True
 Else
 ToggleButton1.Caption = "AutoSize Off"
 TextBox1.AutoSize = False
 TextBox2.AutoSize = False
 End If
End Sub


TextBox Control, SetFocus Method, EnterFieldBehavior, HideSelection, MultiLine, Value Properties Example

 Copy code hover
[image]

TextBox Control, SetFocus Method, EnterFieldBehavior, HideSelection, MultiLine, Value Properties Example
Send feedback

The following example demonstrates the HideSelection property in the context of either a single form or more than one form. The user can select text in a TextBox and TAB to other controls on a form, as well as transfer the focus to a second form. This code sample also uses the SetFocus method, and the EnterFieldBehavior, MultiLine, and Value properties.

To use this example, follow these steps:

  1. Copy this sample code (except for the last event subroutine) to the Declarations portion of a form.

  2. Add a large TextBox named TextBox1, a ToggleButton named ToggleButton1, and a CommandButton named CommandButton1.

  3. Insert a second form into this project named UserForm2.

  4. Paste the last event subroutine of this listing into the Declarations section of UserForm2.

  5. In this form, add a CommandButton named CommandButton1.

  6. Run UserForm1.

Copy code Copy code
' ***** Code for UserForm1 *****
Private Sub CommandButton1_Click()
 TextBox1.SetFocus
 UserForm2.Show 'Bring up the second form.
End Sub
Copy code Copy code
Private Sub ToggleButton1_Click()
 If ToggleButton1.Value = True Then
 TextBox1.HideSelection = False
 ToggleButton1.Caption = "Selection Visible"
 Else
 TextBox1.HideSelection = True
 ToggleButton1.Caption = "Selection Hidden"
 End If
End Sub
Copy code Copy code
Private Sub UserForm_Initialize()
 TextBox1.MultiLine = True
 TextBox1.EnterFieldBehavior = fmEnterFieldBehaviorRecallSelection

'Fill the TextBox
 TextBox1.Text = "SelText indicates the starting " _
 & "point of selected text, or the insertion " _
 & point if no text is selected." & Chr$(10) _
 & Chr$(13) & "The SelStart property is " _
 & "always valid, even when the control does " _
 & "not have focus. Setting SelStart to a " _
 & "value less than zero creates an error. " _
 & Chr$(10) & Chr$(13) & "Changing the value " _
 & "of SelStart cancels any existing " _
 & "selection in the control, places " _
 & "an insertion point in the text, and sets " _
 & "the SelLength property to zero."

 TextBox1.HideSelection = True
 ToggleButton1.Caption = "Selection Hidden"
 ToggleButton1.Value = False

End Sub

'

' ***** Code for UserForm2 *****

Copy code Copy code
Private Sub CommandButton1_Click()
 UserForm2.Hide
End Sub


TextColumn Property Example

 Copy code hover
[image]

TextColumn Property Example
Send feedback

The following example uses the TextColumn property to identify the column of data in a ListBox that supplies data for its Text property. This example sets the third column of the ListBox as the text column. As you select an entry from the ListBox, the value from the TextColumn will be displayed in the Label.

This example also demonstrates how to load a multicolumn ListBox using the AddItem method and the List property.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A ListBox named ListBox1.

  • A TextBox named TextBox1.

Copy code Copy code
Private Sub UserForm_Initialize()
ListBox1.ColumnCount = 3

ListBox1.AddItem "Row 1, Col 1"
ListBox1.List(0, 1) = "Row 1, Col 2"
ListBox1.List(0, 2) = "Row 1, Col 3"

ListBox1.AddItem "Row 2, Col 1"
ListBox1.List(1, 1) = "Row 2, Col 2"
ListBox1.List(1, 2) = "Row 2, Col 3"

ListBox1.AddItem "Row 3, Col 1"
ListBox1.List(2, 1) = "Row 3, Col 2"
ListBox1.List(2, 2) = "Row 3, Col 3"

ListBox1.TextColumn = 3
End Sub

Private Sub ListBox1_Change()
TextBox1.Text = ListBox1.Text
End Sub


TopIndex Property Example

 Copy code hover
[image]

TopIndex Property Example
Send feedback

The following example identifies the top item displayed in a ListBox and the item that has the focus within the ListBox. This example uses the TopIndex property to identify the item displayed at the top of the ListBox and the ListIndex property to identify the item that has the focus. The user selects an item in the ListBox. The displayed values of TopIndex and ListIndex are updated when the user selects an item or when the user clicks the CommandButton..

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Label named Label1.

  • A TextBox named TextBox1.

  • A Label named Label2.

  • A TextBox named TextBox2.

  • A CommandButton named CommandButton1.

  • A ListBox named ListBox1.

Copy code Copy code
Private Sub CommandButton1_Click()
 ListBox1.TopIndex = ListBox1.ListIndex
 TextBox1.Text = ListBox1.TopIndex
 TextBox2.Text = ListBox1.ListIndex
End Sub

Private Sub ListBox1_Change()
 TextBox1.Text = ListBox1.TopIndex
 TextBox2.Text = ListBox1.ListIndex
End Sub

Private Sub UserForm_Initialize()
 Dim i As Integer

 For i = 0 To 24
 ListBox1.AddItem "Choice " & (i + 1)
 Next i
 ListBox1.Height = 66
 CommandButton1.Caption = "Move to top of list"
 CommandButton1.AutoSize = True
 CommandButton1.TakeFocusOnClick = False

 Label1.Caption = "Index of top item"
 TextBox1.Text = ListBox1.TopIndex

 Label2. Caption = "Index of current item"
 Label2.AutoSize = True
 Label2.WordWrap = False
 TextBox2.Text = ListBox1.ListIndex
End Sub


TripleState Property, ToggleButton Control Example

 Copy code hover
[image]

TripleState Property, ToggleButton Control Example
Send feedback

The following example uses the TripleState property to allow Null as a legal value of a CheckBox and a ToggleButton. The user controls the value of TripleState through ToggleButton2. The user can set the value of a CheckBox or ToggleButton based on the value of TripleState.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A CheckBox named CheckBox1.

  • A ToggleButton named ToggleButton1.

  • A ToggleButton named ToggleButton2.

Copy code Copy code
Private Sub UserForm_Initialize()
 CheckBox1.Caption = "Value is True"
 CheckBox1.Value = True
 CheckBox1.TripleState = False

 ToggleButton1.Caption = "Value is True"
 ToggleButton1.Value = True
 ToggleButton1.TripleState = False

 ToggleButton2.Value = False
 ToggleButton2.Caption = "Triple State Off"
End Sub

Private Sub ToggleButton2_Click()
 If ToggleButton2.Value = True Then
 ToggleButton2.Caption = "Triple State On"
 CheckBox1.TripleState = True
 ToggleButton1.TripleState = True
 Else
 ToggleButton2.Caption = "Triple State Off"
 CheckBox1.TripleState = False
 ToggleButton1.TripleState = False
 End If
End Sub

Private Sub CheckBox1_Change()
 If IsNull(CheckBox1.Value) Then
 CheckBox1.Caption = "Value is Null"
 ElseIf CheckBox1.Value = False Then
 CheckBox1.Caption = "Value is False"
 ElseIf CheckBox1.Value = True Then
 CheckBox1.Caption = "Value is True"
 End If
End Sub

Private Sub ToggleButton1_Change()
 If IsNull(ToggleButton1.Value) Then
 ToggleButton1.Caption = "Value is Null"
 ElseIf ToggleButton1.Value = False Then
 ToggleButton1.Caption = "Value is False"
 ElseIf ToggleButton1.Value = True Then
 ToggleButton1.Caption = "Value is True"
 End If
End Sub


Value Property Example

 Copy code hover
[image]

Value Property Example
Send feedback

The following example demonstrates the values that the different types of controls can have by displaying the Value property of a selected control. The user chooses a control by pressing TAB or by clicking on the control. Depending on the type of control, the user can also specify a value for the control by typing in the text area of the control, by clicking one or more times on the control, or by selecting an item, page, or tab within the control. The user can display the value of the selected control by clicking the appropriately labeled CommandButton.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A CommandButton named CommandButton1.

  • A TextBox named TextBox1.

  • A CheckBox named CheckBox1.

  • A ComboBox named ComboBox1.

  • A CommandButton named CommandButton2.

  • A ListBox named ListBox1.

  • A MultiPage named MultiPage1.

  • Two OptionButton controls named OptionButton1 and OptionButton2.

  • A ScrollBar named ScrollBar1.

  • A SpinButton named SpinButton1.

  • A TabStrip named TabStrip1.

  • A TextBox named TextBox2.

  • A ToggleButton named ToggleButton1.

Copy code Copy code
Dim i As Integer

Private Sub CommandButton1_Click()
 TextBox1.Text = "Value of " & ActiveControl.Name _
 & " is " & ActiveControl.Value
End Sub

Private Sub UserForm_Initialize()
 CommandButton1.Caption = "Get value of " _
 & "current control"
 CommandButton1.AutoSize = True
 CommandButton1.TakeFocusOnClick = False
 CommandButton1.TabStop = False

 TextBox1.AutoSize = True

 For i = 0 To 10
 ComboBox1.AddItem "Choice " & (i + 1)
 ListBox1.AddItem "Selection " & (100 - i)
 Next i

 CheckBox1.TripleState = True
 ToggleButton1.TripleState = True

 TextBox2.Text = "Enter text here."
End Sub


Zoom Event, Zoom Property, Label Control Example

 Copy code hover
[image]

Zoom Event, Zoom Property, Label Control Example
Send feedback

The following example uses the Zoom event to evaluate the new value of the Zoom property and adds scroll bars to the form when appropriate. The example uses a Label to display the current value. The user specifies the size for the form by using the SpinButton and then clicks the CommandButton to set the value in the Zoom property.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • A Label named Label1.

  • A SpinButton named SpinButton1.

  • A CommandButton named CommandButton1.

  • Other controls placed near the edges of the form.

Copy code Copy code
Private Sub CommandButton1_Click()
 Zoom = SpinButton1.Value
End Sub

Private Sub SpinButton1_SpinDown()
 Label1.Caption = SpinButton1.Value
End Sub

Private Sub SpinButton1_SpinUp()
 Label1.Caption = SpinButton1.Value
End Sub

Private Sub UserForm_Initialize()
 SpinButton1.Min = 10
 SpinButton1.Max = 400
 SpinButton1.Value = 100
 Label1.Caption = SpinButton1.Value

 CommandButton1.Caption = "Zoom it!"
End Sub

Private Sub UserForm_Zoom(Percent As Integer)
 Dim MyResult As Double

 If Percent > 99 Then
 ScrollBars = fmScrollBarsBoth
 ScrollLeft = 0
 ScrollTop = 0

 MyResult = Width * Percent / 100
 ScrollWidth = MyResult

 MyResult = Height * Percent / 100
 ScrollHeight = MyResult
 Else
 ScrollBars = fmScrollBarsNone
 ScrollLeft = 0
 ScrollTop = 0
 End If
End Sub


ZOrder Method, TextBox Control Example

 Copy code hover
[image]

ZOrder Method, TextBox Control Example
Send feedback

The following example sets the z-order of a TextBox, so the user can display the entire TextBox (by bringing it to the front of the z-order) or can place the TextBox behind other controls (by sending it to the back of the z-order).

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

  • Three TextBox controls named TextBox1 through TextBox3.

  • A ToggleButton named ToggleButton1.

Copy code Copy code
Private Sub ToggleButton1_Click()
If ToggleButton1.Value = True Then
 TextBox2.ZOrder(fmTop)
 'Place TextBox2 on Top of z-order

 'Update ToggleButton caption to identify next state
 ToggleButton1.Caption = "Send TextBox2 to back"
Else
 TextBox2.ZOrder(1)
 'Place TextBox2 on Bottom of z-order

 'Update ToggleButton caption to identify next state
 ToggleButton1.Caption = "Bring TextBox2 to front"
End If
End Sub
Copy code Copy code
Private Sub UserForm_Initialize()
'Set up text boxes to show z-order in the form
TextBox1.Text = "TextBox 1"
TextBox2.Text = "TextBox 2"
TextBox3.Text = "TextBox 3"

TextBox1.Height = 40
TextBox2.Height = 40
TextBox3.Height = 40

TextBox1.Width = 60
TextBox2.Width = 60
TextBox3.Width = 60

TextBox1.Left = 10
TextBox1.Top = 10

TextBox2.Left = 25 'Overlap TextBox2 on TextBox1
TextBox2.Top = 25

TextBox3.Left = 40 'Overlap TextBox3 on TextBox2, TextBox1
TextBox3.Top = 40

ToggleButton1.Value = False
ToggleButton1.Caption = "Bring TextBox2 to Front"
ToggleButton1.Left = 10
ToggleButton1.Top = 90
ToggleButton1.Width = 50
ToggleButton1.Height = 50

End Sub


Methods (Microsoft Forms)

 Copy code hover
[image]

Methods (Microsoft Forms)
Send feedback

In this section

  • Add Method (Microsoft Forms)

  • AddItem Method

  • Clear Method (Microsoft Forms)

  • Copy Method (Microsoft Forms)

  • Cut Method (Microsoft Forms)

  • DropDown Method

  • GetFormat Method

  • GetFromClipboard Method

  • GetText Method (Microsoft Forms)

  • Item Method (Microsoft Forms)

  • Move Method

  • Paste Method (Microsoft Forms)

  • PutInClipboard Method

  • RedoAction Method

  • Remove Method

  • RemoveItem Method

  • Repaint Method

  • Scroll Method

  • SetDefaultTabOrder Method

  • SetFocus Method

  • SetText Method

  • StartDrag Method

  • UndoAction Method

  • ZOrder Method


Add Method (Microsoft Forms)

 Copy code hover
[image]

Add Method (Microsoft Forms)
Send feedback

Adds or inserts a Tab or Page in a TabStrip or MultiPage, or adds a control by its programmatic identifier (ProgID) to a page or form.

Syntax

For MultiPage, TabStrip
Set Object = object.Add( [ Name [, Caption [, index]]])

For other controls
Set Control = object.Add( ProgID [, Name [, Visible]])

The Add method syntax has these parts:

Part | Description
object | Required. A valid object name.
Name | Optional. Specifies the name of the object being added. If a name is not specified, the system generates a default name based on the rules of the application where the form is used.
Caption | Optional. Specifies the caption to appear on a tab or a control. If a caption is not specified, the system generates a default caption based on the rules of the application where the form is used.
index | Optional. Identifies the position of a page or tab within a Pages or Tabs collection. If an index is not specified, the system appends the page or tab to the end of the Pages or Tabs collection and assigns the appropriate index value.
ProgID | Required. Programmatic identifier. A text string with no spaces that identifies an object class. The standard syntax for a ProgID is <Vendor>.<Component>.<Version>. A ProgID is mapped to a class identifier (CLSID).
Visible | Optional. True if the object is visible (default). False if the object is hidden.

Settings

ProgID values for individual controls are:

CheckBox | Forms.CheckBox.1
ComboBox | Forms.ComboBox.1
CommandButton | Forms.CommandButton.1
Frame | Forms.Frame.1
Image | Forms.Image.1
Label | Forms.Label.1
ListBox | Forms.ListBox.1
MultiPage | Forms.MultiPage.1
OptionButton | Forms.OptionButton.1
ScrollBar | Forms.ScrollBar.1
SpinButton | Forms.SpinButton.1
TabStrip | Forms.TabStrip.1
TextBox | Forms.TextBox.1
ToggleButton | Forms.ToggleButton.1

Remarks

For a MultiPage control, the Add method returns a Page object. For a TabStrip, it returns a Tab object. The index value for the first Page or Tab of a collection is 0, the value for the second Page or Tab is 1, and so on.

For the Controls collection of an object, the Add method returns a control corresponding to the specified ProgID. The AddControl event occurs after the control is added.

You can add a control to a user form's Controls collection at design time, but you must use the Designer property of the Microsoft Visual Basic for Applications Extensibility Library to do so. The Designer property returns the UserForm object.

The following syntax will return the Text property of the specified control:

VBA Copy code Copy code
userform1.thebox.text

If you add a control at run time, you must use the exclamation syntax to reference properties of that control. For example, to return the Text property of a control added at run time, use the following syntax:

VBA Copy code Copy code
userform1!thebox.text
Note Note

You can change a control's Name property at run time only if you added that control at run time with the Add method.


AddItem Method

 Copy code hover
[image]

AddItem Method
Send feedback

For a single-column list box or combo box, adds an item to the list. For a multicolumn list box or combo box, adds a row to the list.

Syntax

Variant = object.AddItem [ item [, varIndex]]

The AddItem method syntax has these parts:

Part | Description
object | Required. A valid object.
Item | Optional. Specifies the item or row to add. The number of the first item or row is 0; the number of the second item or row is 1, and so on.
varIndex | Optional. Integer specifying the position within the object where the new item or row is placed.

Remarks

If you supply a valid value for varIndex, the AddItem method places the item or row at that position within the list. If you omit varIndex, the method adds the item or row at the end of the list.

The value of varIndex must not be greater than the value of the ListCount property.

For a multicolumn ListBox or ComboBox, AddItem inserts an entire row, that is, it inserts an item for each column of the control. To assign values to an item beyond the first column, use the List or Column property and specify the row and column of the item.

If the control is bound to data, the AddItem method fails.

Note Note

You can add more than one row at a time to a ComboBox or ListBox by using List.


Clear Method (Microsoft Forms)

 Copy code hover
[image]

Clear Method (Microsoft Forms)
Send feedback

Removes all objects from an object or collection.

Syntax

object.Clear

The Clear method syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

For a MultiPage or TabStrip, the Clear method deletes individual pages or tabs.

For a ListBox or ComboBox, Clear removes all entries in the list.

For a Controls collection, Clear deletes controls that were created at run time with the Add method. Using Clear on controls created at design time causes an error.

If the control is bound to data, the Clear method fails.


Copy Method (Microsoft Forms)

 Copy code hover
[image]

Copy Method (Microsoft Forms)
Send feedback

Copies the contents of an object to the Clipboard.

Syntax

object.Copy

The Copy method syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

The original content remains on the object.

The actual content that is copied depends on the object. For example, on a Page, the Copy method copies the currently selected control or controls. On a TextBox or ComboBox, it copies the currently selected text.

Using Copy for a form, Frame, or Page copies the currently-active control.


Cut Method (Microsoft Forms)

 Copy code hover
[image]

Cut Method (Microsoft Forms)
Send feedback

Removes selected information from an object and transfers it to the Clipboard.

Syntax

object.Cut

The Cut method syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

For a ComboBox or TextBox, the Cut method removes currently selected text in the control to the Clipboard. This method does not require that the control have the focus.

On a Page, Frame, or form, Cut removes currently selected controls to the Clipboard. This method only removes controls created at run time.


DropDown Method

 Copy code hover
[image]

DropDown Method
Send feedback

Displays the list portion of a ComboBox.

Syntax

object.DropDown

The DropDown method syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

Use the DropDown method to open the list in a combo box.


GetFormat Method

 Copy code hover
[image]

GetFormat Method
Send feedback

Returns an integer value indicating whether a specific format is on the DataObject.

Syntax

Boolean = object.GetFormat( format)

The GetFormat method syntax has these parts:

Part | Description
object | Required. A valid object.
format | Required. An integer or string specifying a specific format that might exist in the DataObject. If the specified format exists in the DataObject, GetFormat returns True.

Settings

The settings for format are:

Value | Description
1 | Text format.
A string or any integer other than 1 | A user-defined DataObject format passed to the DataObject from SetText.

Remarks

The GetFormat method searches for a format in the current list of formats on the DataObject. If the format is on the DataObject, GetFormat returns True; if not, GetFormat returns False.

The DataObject currently supports only text formats.


GetFromClipboard Method

 Copy code hover
[image]

GetFromClipboard Method
Send feedback

Copies data from the Clipboard to a DataObject.

Syntax

String = object.GetFromClipboard( )

The GetFromClipboard method syntax has these parts:

Part | Description
object | Required. A valid object name.

Remarks

The DataObject can contain multiple data items, but each item must be in a different format. For example, the DataObject might include one text item and one item in a custom format; but cannot include two text items.


GetText Method (Microsoft Forms)

 Copy code hover
[image]

GetText Method (Microsoft Forms)
Send feedback

Retrieves a text string from the DataObject using the specified format.

Syntax

String = object.GetText( [ format])

The GetText method syntax has these parts:

Part | Description
object | Required. A valid object name.
format | Optional. A string or integer specifying the format of the data to retrieve from the DataObject.

Settings

The settings for format are:

Value | Description
1 | Text format.
A string or any integer other than 1 | A user-defined DataObject format passed to the DataObject from SetText.

Remarks

The DataObject supports multiple formats, but only supports one data item of each format. For example, the DataObject might include one text item and one item in a custom format; but cannot include two text items.

If no format is specified, the GetText method requests information in the Text format from the DataObject.


Item Method (Microsoft Forms)

 Copy code hover
[image]

Item Method (Microsoft Forms)
Send feedback

Returns a member of a collection, either by position or by name.

Syntax

Set Object = object.Item( collectionindex)

The Item method syntax has these parts:

Part | Description
object | Required. A valid object.
collectionindex | Required. A member's position, or index, within a collection.

Settings

The collectionindex can be either a string or an integer. If it is a string, it must be a valid member name. If it is an integer, the minimum value is 0 and the maximum value is one less than the number of items in the collection.

Remarks

If an invalid index or name is specified, an error occurs.


Move Method

 Copy code hover
[image]

Move Method
Send feedback

Moves a form or control, or moves all the controls in the Controls collection.

Syntax

For a form or control
object.Move( [Left [, Top [, Width [, Height [, Layout]]]]])

For the Controls collection
object.Move( X, Y)

The Move method syntax has these parts:

Part | Description
object | Required. A valid object name.
Left | Optional. Single-precision value, in points, indicating the horizontal coordinate for the left edge of the object.
Top | Optional. Single-precision value, in points, that specifies the vertical coordinate for the top edge of the object.
Width | Optional. Single-precision value, in points, indicating the width of the object.
Height | Optional. Single-precision value, in points, indicating the height of the object.
Layout | Optional. A Boolean value indicating whether the Layout event is initiated for the control's parent following this move. False is the default value.
X, Y | Required. Single-precision value, in points, that specifies the change from the current horizontal and vertical position for each control in the Controls collection.

Settings

The maximum and minimum values for the Left, Top, Width, Height, X, and Y arguments vary from one application to another.

Remarks

For a form or control, you can move a selection to a specific location relative to the edges of the form that contains the selection.

You can use named arguments, or you can enter the arguments by position. If you use named arguments, you can list the arguments in any order. If not, you must enter the arguments in the order shown, using commas to indicate the relative position of arguments you do not specify. Any unspecified arguments remain unchanged.

For the Controls collection, you can move all the controls in this collection a specific distance from their current positions on a form, Frame, or Page.


Paste Method (Microsoft Forms)

 Copy code hover
[image]

Paste Method (Microsoft Forms)
Send feedback

Transfers the contents of the Clipboard to an object.

Syntax

object.Paste

The Paste method syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

Data pasted into a ComboBox or TextBox is treated as text.

When the paste method is used with a form, you can paste any object onto the form.


PutInClipboard Method

 Copy code hover
[image]

PutInClipboard Method
Send feedback

Moves data from a DataObject to the Clipboard.

Syntax

object.PutInClipboard

The PutInClipboard method syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

The PutInClipboard method replaces the contents of the Clipboard with the contents of the DataObject that is in Text format.


RedoAction Method

 Copy code hover
[image]

RedoAction Method
Send feedback

Reverses the effect of the most recent Undo action.

Syntax

Boolean = object.RedoAction

The RedoAction method syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

Redo reverses the last Undo, which is not necessarily the last action taken. Not all actions can be undone.

For example, after pasting text into a TextBox and then choosing the Undo command to remove the text, you can choose the Redo command to put the text back in.

Note Note

If the CanRedo property is False, the Redo command is not available in the user interface, and the RedoAction method is not valid in code.

RedoAction returns True if it was successful.


Remove Method

 Copy code hover
[image]

Remove Method
Send feedback

Removes a member from a collection; or, removes a control from a Frame, Page, or form.

Syntax

object.Remove( collectionindex)

The Remove method syntax has these parts:

Part | Description
object | Required. A valid object.
collectionindex | Required. A member's position, or index, within a collection. Numeric as well as string values are acceptable. If the value is a number, the minimum value is zero, and the maximum value is one less than the number of members in the collection. If the value is a string, it must correspond to a valid member name.

Remarks

This method deletes any control that was added at run time. However, attempting to delete a control that was added at design time will result in an error.


RemoveItem Method

 Copy code hover
[image]

RemoveItem Method
Send feedback

Removes a row from the list in a list box or combo box.

Syntax

Boolean = object.RemoveItem index

The RemoveItem method syntax has these parts:

Part | Description
object | Required. A valid object.
index | Required. Specifies the row to delete. The number of the first row is 0; the number of the second row is 1, and so on.

This method will not remove a row from the list if the ListBox is data bound (that is, when the RowSource property specifies a data source for the ListBox).


Repaint Method

 Copy code hover
[image]

Repaint Method
Send feedback

Updates the display by redrawing the form or page.

Syntax

Boolean = object.Repaint

The Repaint method syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

The Repaint method is useful if the contents or appearance of an object changes significantly, and you don't want to wait until the system automatically repaints the area.


Scroll Method

 Copy code hover
[image]

Scroll Method
Send feedback

Moves the scroll bar on an object.

Syntax

object.Scroll( [ ActionX [, ActionY]])

The Scroll method syntax has these parts:

Part | Description
object | Required. A valid object name.
ActionX | Optional. Identifies the action to occur in the horizontal direction.
ActionY | Optional. Identifies the action to occur in the vertical direction.

Settings

The settings for ActionX and ActionY are:

Constant | Value | Description
fmScrollActionNoChange | 0 | Do not scroll in the specified direction.
fmScrollActionLineUp | 1 | Move up on a vertical scroll bar or left on a horizontal scroll bar. Movement is equivalent to pressing the up or left arrow key on the keyboard to move the scroll bar.
fmScrollActionLineDown | 2 | Move down on a vertical scroll bar or right on a horizontal scroll bar. Movement is equivalent to pressing the right or down arrow key on the keyboard to move the scroll bar.
fmScrollActionPageUp | 3 | Move one pageup on a vertical scroll bar or one page left on a horizontal scroll bar. Movement is equivalent to pressing PAGE UP on the keyboard to move the scroll bar.
fmScrollActionPageDown | 4 | Move one pagedown on a vertical scroll bar or one page right on a horizontal scroll bar. Movement is equivalent to pressing PAGE DOWN on the keyboard to move the scroll bar.
fmScrollActionBegin | 5 | Move to the top of a vertical scroll bar or to the left end of a horizontal scroll bar.
fmScrollActionEnd | 6 | Move to the bottom of a vertical scroll bar or to the right end of a horizontal scroll bar.

Remarks

The Scroll method applies scroll bars that appear on a form, Frame, or Page that is larger than its display area. This method does not apply to the stand-alone ScrollBar or to scroll bars that appear on a TextBox.


SetDefaultTabOrder Method

 Copy code hover
[image]

SetDefaultTabOrder Method
Send feedback

Sets the TabIndex property of each control on a form, using a default top-to-bottom, left-to-right tab order.

Syntax

object.SetDefaultTabOrder

The SetDefaultTabOrder method syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

Microsoft Forms sets the tab order beginning with controls in the upper left corner of the form and moving to the right. It places controls closest to the left edge of the form earlier in the tab order. If more than one control is the same distance from the left edge of the form, tab order values are assigned from top to bottom.


SetFocus Method

 Copy code hover
[image]

SetFocus Method
Send feedback

Moves the focus to this instance of an object.

Syntax

object.SetFocus

The SetFocus method syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

If setting the focus fails, the focus reverts to the previous object and an error is generated.

By default, setting the focus to a control does not activate the control's window or place it on top of other controls.

The SetFocus method is valid for an empty Frame as well as a Frame that contains other controls. An empty Frame will take the focus itself, and any subsequent keyboard events apply to the Frame. In a Frame that contains other controls, the focus moves to the first control in the Frame, and subsequent keyboard events apply to the control that has the focus.


SetText Method

 Copy code hover
[image]

SetText Method
Send feedback

Copies a text string to the DataObject using a specified format.

Syntax

object.SetText( StoreData [, format])

The SetText method syntax has these parts:

Part | Description
object | Required. A valid object.
StoreData | Required. Defines the data to store on the DataObject.
format | Optional. An integer or string specifying the format of StoreData. When retrieving data from the DataObject, the format identifies the piece of data to retrieve.

Settings

The settings for format are:

Value | Description
1 | Text format.
A string or integer value other than 1 | A user-defined DataObject format.

Remarks

The DataObject stores data according to its format. When the user supplies a string, the DataObject saves the text under the specified format.

If the DataObject contains data in the same format as new data, the new data replaces the existing data in the DataObject. If the new data is in a new format, the new data and the new format are both added to the DataObject, and the previously existing data is there as well.

If no format is specified, the SetText method assigns the Text format to the text string. If a new format is specified, the DataObject registers the new format with the system.


StartDrag Method

 Copy code hover
[image]

StartDrag Method
Send feedback

Initiates a drag-and-drop operation for a DataObject.

Syntax

fmDropEffect=Object.StartDrag([Effect as fmDropEffect])

The StartDrag method syntax has these parts:

Part | Description
Object | Required. A valid object.
Effect | Optional. Effect of the drop operation on the target control.

Settings

The settings for Effect are:

Constant | Value | Description
fmDropEffectNone | 0 | Does not copy or move the drop source to the drop target.
fmDropEffectCopy | 1 | Copies the drop source to the drop target.
fmDropEffectMove | 2 | Moves the drop source to the drop target.
fmDropEffectCopyOrMove | 3 | Copies or moves the drop source to the drop target.

Remarks

The drag action starts at the current mouse pointer position with the current keyboard state and ends when the user releases the mouse. The effect of the drag-and-drop operation depends on the effect chosen for the drop target.

For example, a control's MouseMove event might include the StartDrag method. When the user clicks the control and moves the mouse, the mouse pointer changes to indicate whether Effect is valid for the drop target.


UndoAction Method

 Copy code hover
[image]

UndoAction Method
Send feedback

Reverses the most recent action that supports the Undo command.

Syntax

Boolean = object.UndoAction

The UndoAction method syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

The Undo command in the user interface uses the UndoAction method. For example, if you paste text into a TextBox, you can use UndoAction to remove that text and restore the previous contents of the TextBox.

Not all user actions can be undone. If an action cannot be undone, the Undo command is unavailable following the action.

Note Note

If the CanUndo property is False, the Undo command is not available in the user interface, and UndoAction is not valid in code.

If UndoAction is applied to a form, all changes to the current record are lost. If UndoAction is applied to a control, only the control itself is affected.

You must apply this method before the form or control is updated. You may want to include this method in a form's BeforeUpdate event or a control's Change event.

UndoAction is an alternative to using the SendKeys Statement to send the value of ESC in an event procedure.


ZOrder Method

 Copy code hover
[image]

ZOrder Method
Send feedback

Places the object at the front or back of the z-order.

Syntax

object.ZOrder( [ zPosition])

The ZOrder method syntax has these parts:

Part | Description
object | Required. A valid object.
zPosition | Optional. A control's position, front or back, in the container's z-order.

Settings

The settings for zPosition are:

Constant | Value | Description
fmTop | 0 | Places the control at the front of the z-order. The control appears on top of other controls (default).
fmBottom | 1 | Places the control at the back of the z-order. The control appears underneath other controls.

Remarks

The z-order determines how windows and controls are stacked when they are presented to the user. Items at the back of the z-order are overlaid by closer items; items at the front of the z-order appear to be on top of items at the back. When the zPosition argument is omitted, the object is brought to the front.

In design mode, the Bring to Front or Send To Back commands set the z-order. Bring to Front is equivalent to using the ZOrder method and putting the object at the front of the z-order. Send to Back is equivalent to using ZOrder and putting the object at the back of the z-order.

This method does not affect content or sequence of the controls in the Controls collection.

Note Note

You can't Undo or Redo layering commands, such as Send to Back or Bring to Front. For example, if you select an object and click Move Backward on the shortcut menu, you won't be able to Undo or Redo that action.


Objects (Microsoft Forms)

 Copy code hover
[image]

Objects (Microsoft Forms)
Send feedback

In this section

  • CheckBox Control

  • ComboBox Control

  • CommandButton Control

  • DataObject Object

  • Font Object (Microsoft Forms)

  • Frame Control

  • Image Control

  • Label Control

  • ListBox Control

  • MultiPage Control

  • OptionButton Control

  • Page Object

  • ScrollBar Control

  • SpinButton Control

  • Tab Object

  • TabStrip Control

  • TextBox Control

  • ToggleButton Control

  • UserForm Window


CheckBox Control

 Copy code hover
[image]

CheckBox Control
Send feedback

Displays the selection state of an item.

Remarks

Use a CheckBox to give the user a choice between two values such as Yes/No, True/False, or On/Off. When the user selects a CheckBox, it displays a special mark (such as an X) and its current setting is Yes, True, or On; if the user does not select the CheckBox, it is empty and its setting is No, False, or Off. Depending on the value of the TripleState property, a CheckBox can also have a null value.

If a CheckBox is bound to a data source, changing the setting changes the value of that source. A disabled CheckBox shows the current value, but is dimmed and does not allow changes to the value from the user interface.

You can also use check boxes inside a group box to select one or more of a group of related items. For example, you can create an order form that contains a list of available items, with a CheckBox preceding each item. The user can select a particular item or items by checking the corresponding CheckBox.

The default property of a CheckBox is the Value property.

The default event of a CheckBox is the Click event.

Note Note

The ListBox also lets you put a check mark by selected options. Depending on your application, you can use the ListBox instead of using a group of CheckBox controls.


ComboBox Control

 Copy code hover
[image]

ComboBox Control
Send feedback

Combines the features of a ListBox and a TextBox. The user can enter a new value, as with a TextBox, or the user can select an existing value as with a ListBox.

Remarks

If a ComboBox is bound to a data source, then the ComboBox inserts the value the user enters or selects into that data source. If a multicolumn combo box is bound, then the BoundColumn property determines which value is stored in the bound data source.

The list in a ComboBox consists of rows of data. Each row can have one or more columns, which can appear with or without headings. Some applications do not support column headings, others provide only limited support.

The default property of a ComboBox is the Value property.

The default event of a ComboBox is the Change event.

Note Note

If you want more than a single line of the list to appear at all times, you might want to use a ListBox instead of a ComboBox. If you want to use a ComboBox and limit values to those in the list, you can set the Style property of the ComboBox so the control looks like a drop-down list box.


CommandButton Control

 Copy code hover
[image]

CommandButton Control
Send feedback

Starts, ends, or interrupts an action or series of actions.

Remarks

The macro or event procedure assigned to the CommandButton's Click event determines what the CommandButton does. For example, you can create a CommandButton that opens another form. You can also display text, a picture, or both on a CommandButton.

The default property of a CommandButton is the Value property.

The default event for a CommandButton is the Click event.


DataObject Object

 Copy code hover
[image]

DataObject Object
Send feedback

A holding area for formatted text data used in transfer operations. Also holds a list of formats corresponding to the pieces of text stored in the DataObject.

Remarks

A DataObject can contain one piece of text for the Clipboard text format, and one piece of text for each additional text format, such as custom and user-defined formats.

A DataObject is distinct from the Clipboard. A DataObject supports commands that involve the Clipboard and drag-and-drop actions for text. When you start an operation involving the Clipboard (such as GetText) or a drag-and-drop operation, the data involved in that operation is moved to a DataObject.

The DataObject works like the Clipboard. If you copy a text string to a DataObject, the DataObject stores the text string. If you copy a second string of the same format to the DataObject, the DataObject discards the first text string and stores a copy of the second string. It stores one piece of text of a specified format and keeps the text from the most recent operation.


Font Object (Microsoft Forms)

 Copy code hover
[image]

Font Object (Microsoft Forms)
Send feedback

Defines the characteristics of the text used by a control or form.

Remarks

Each control or form has its own Font object to let you set its text characteristics independently of the characteristics defined for other controls and forms. Use font properties to specify the font name, to set bold or underlined text, or to adjust the size of the text.

Note Note

The font properties of your form or container determine the default font attributes of controls you put on the form.

The default property for the Font object is the Name property. If the Name property contains a null string, the Font object uses the default system font.


Frame Control

 Copy code hover
[image]

Frame Control
Send feedback

Creates a functional and visual control group.

Remarks

All option buttons in a Frame are mutually exclusive, so you can use the Frame to create an option group. You can also use a Frame to group controls with closely related contents.For example, in an application that processes customer orders, you might use a Frame to group the name, address, and account number of customers.

You can also use a Frame to create a group of toggle buttons, but the toggle buttons are not mutually exclusive.

The default event for a Frame is the Click event.


Image Control

 Copy code hover
[image]

Image Control
Send feedback

Displays a picture on a form.

Remarks

The Image lets you display a picture as part of the data in a form. For example, you might use an Image to display employee photographs in a personnel form.

The Image lets you crop, size, or zoom a picture, but does not allow you to edit the contents of the picture. For example, you cannot use the Image to change the colors in the picture, to make the picture transparent, or to refine the image of the picture. You must use image editing software for these purposes.

The Image supports the following file formats:

  • *.bmp

  • *.cur

  • *.gif

  • *.ico

  • *.jpg

  • *.wmf

Note Note

You can also display a picture on a Label. However, a Label does not let you crop, size, or zoom the picture.

The default event for the Image is the Click event.


Label Control

 Copy code hover
[image]

Label Control
Send feedback

Displays descriptive text.

Remarks

A Label control on a form displays descriptive text such as titles, captions, pictures, or brief instructions. For example, labels for an address book might include a Label for a name, street, or city. A Label doesn't display values from data sources or expressions; it is always unbound and doesn't change as you move from record to record.

The default property for a Label is the Caption property.

The default event for a Label is the Click event.


ListBox Control

 Copy code hover
[image]

ListBox Control
Send feedback

Displays a list of values and lets you select one or more.

Remarks

If the ListBox is bound to a data source, then the ListBox stores the selected value in that data source.

The ListBox can either appear as a list or as a group of OptionButton controls or CheckBox controls.

The default property for a ListBox is the Value property.

The default event for a ListBox is the Click event.

Note Note

You can't drop text into a drop-down ListBox.


MultiPage Control

 Copy code hover
[image]

MultiPage Control
Send feedback

Presents multiple screens of information as a single set.

Remarks

A MultiPage is useful when you work with a large amount of information that can be sorted into several categories. For example, use a MultiPage to display information from an employment application. One page might contain personal information such as name and address; another page might list previous employers; a third page might list references. The MultiPage lets you visually combine related information, while keeping the entire record readily accessible.

New pages are added to the right of the currently selected page rather than adjacent to it.

Note Note

The MultiPage is a container of a Pages collection, each of which contains one or more Page objects.

The default property for a MultiPage is the Value property, which returns the index of the currently active Page in the Pages collection of the MultiPage.

The default event for a MultiPage is the Change event.


OptionButton Control

 Copy code hover
[image]

OptionButton Control
Send feedback

Shows the selection status of one item in a group of choices.

Remarks

Use an OptionButton to show whether a single item in a group is selected. Note that each OptionButton in a Frame is mutually exclusive.

If an OptionButton is bound to a data source, the OptionButton can show the value of that data source as either Yes/No, True/False, or On/Off. If the user selects the OptionButton, the current setting is Yes, True, or On; if the user does not select the OptionButton, the setting is No, False, or Off. For example, an OptionButton in an inventory-tracking application might show whether an item is discontinued. If the OptionButton is bound to a data source, then changing the settings changes the value of that data source. A disabled OptionButton is dimmed and does not show a value.

Depending on the value of the TripleState property, an OptionButton can also have a null value.

You can also use an OptionButton inside a group box to select one or more of a group of related items. For example, you can create an order form with a list of available items, with an OptionButton preceding each item. The user can select a particular item by checking the corresponding OptionButton.

The default property for an OptionButton is the Value property.

The default event for an OptionButton is the Click event.


Page Object

 Copy code hover
[image]

Page Object
Send feedback

One page of a MultiPage and a single member of a Pages collection.

Remarks

Each Page object contains its own set of controls and does not necessarily rely on other pages in the collection for information. A Page inherits some properties from its container; the value of each inherited property is set by the container.

A Page has a unique name and index value within a Pages collection. You can reference a Page by either its name or its index value. The index of the first Page in a collection is 0; the index of the second Page is 1; and so on. When two Page objects have the same name, you must reference each Page by its index value. References to the name in code will access only the first Page that uses the name.

The default name for the first Page is Page1; the default name for the second Page is Page2.


ScrollBar Control

 Copy code hover
[image]

ScrollBar Control
Send feedback

Returns or sets the value of another control based on the position of the scroll box.

Remarks

A ScrollBar is a stand-alone control you can place on a form. It is visually like the scroll bar you see in certain objects such as a ListBox or the drop-down portion of a ComboBox. However, unlike the scroll bars in these examples, the stand-alone ScrollBar is not an integral part of any other control.

To use the ScrollBar to set or read the value of another control, you must write code for the ScrollBar's events and methods. For example, to use the ScrollBar to update the value of a TextBox, you can write code that reads the Value property of the ScrollBar and then sets the Value property of the TextBox.

The default property for a ScrollBar is the Value property.

The default event for a ScrollBar is the Change event.

Note Note

To create a horizontal or vertical ScrollBar, drag the sizing handles of the ScrollBar horizontally or vertically on the form.


SpinButton Control

 Copy code hover
[image]

SpinButton Control
Send feedback

Increments and decrements numbers.

Remarks

Clicking a SpinButton changes only the value of the SpinButton. You can write code that uses the SpinButton to update the displayed value of another control. For example, you can use a SpinButton to change the month, the day, or the year shown on a date. You can also use a SpinButton to scroll through a range of values or a list of items, or to change the value displayed in a text box.

To display a value updated by a SpinButton, you must assign the value of the SpinButton to the displayed portion of a control, such as the Caption property of a Label or the Text property of a TextBox. To create a horizontal or vertical SpinButton, drag the sizing handles of the SpinButton horizontally or vertically on the form.

The default property for a SpinButton is the Value property.

The default event for a SpinButton is the Change event.


Tab Object

 Copy code hover
[image]

Tab Object
Send feedback

A Tab is an individual member of a Tabs collection.

Remarks

Visually, a Tab object appears as a rectangle protruding from a larger rectangular area or as a button adjacent to a rectangular area.

In contrast to a Page, a Tab does not contain any controls. Controls that appear within the region bounded by a TabStrip are contained on the form, as is the TabStrip.

Each Tab has its own set of properties, but has no methods or events. You must use events from the appropriate TabStrip to initiate processing of an individual Tab.

Each Tab has a unique name and index value within the collection. You can reference a Tab by either its name or its index value. The index of the first Tab is 0; the index of the second Tab is 1; and so on. When two Tab objects have the same name, you must reference each Tab by its index value. References to the name in code will access only the first Tab that uses the name.


TabStrip Control

 Copy code hover
[image]

TabStrip Control
Send feedback

Presents a set of related controls as a visual group.

Remarks

You can use a TabStrip to view different sets of information for related controls.

For example, the controls might represent information about a daily schedule for a group of individuals, with each set of information corresponding to a different individual in the group. Set the title of each tab to show one individual's name. Then, you can write code that, when you click a tab, updates the controls to show information about the person identified on the tab.

Note Note

The TabStrip is implemented as a container of a Tabs collection, which in turn contains a group of Tab objects.

The default property for a TabStrip is the SelectedItem property.

The default event for a TabStrip is the Change event.


TextBox Control

 Copy code hover
[image]

TextBox Control
Send feedback

Displays information from a user or from an organized set of data.

Remarks

A TextBox is the control most commonly used to display information entered by a user. Also, it can display a set of data, such as a table, query, worksheet, or a calculation result. If a TextBox is bound to a data source, then changing the contents of the TextBox also changes the value of the bound data source.

Formatting applied to any piece of text in a TextBox will affect all text in the control. For example, if you change the font or point size of any character in the control, the change will affect all characters in the control.

The default property for a TextBox is the Value property.

The default event for a TextBox is the Change event.


ToggleButton Control

 Copy code hover
[image]

ToggleButton Control
Send feedback

Shows the selection state of an item.

Remarks

Use a ToggleButton to show whether an item is selected. If a ToggleButton is bound to a data source, the ToggleButton shows the current value of that data source as either Yes/No, True/False, On/Off, or some other choice of two settings. If the user selects the ToggleButton, the current setting is Yes, True, or On; if the user does not select the ToggleButton, the setting is No, False, or Off. If the ToggleButton is bound to a data source, changing the setting changes the value of that data source. A disabled ToggleButton shows a value, but is dimmed and does not allow changes from the user interface.

You can also use a ToggleButton inside a Frame to select one or more of a group of related items. For example, you can create an order form with a list of available items, with a ToggleButton preceding each item. The user can select a particular item by selecting the appropriate ToggleButton.

The default property of a ToggleButton is the Value property.

The default event of a ToggleButton is the Click event.


UserForm Window

 Copy code hover
[image]

UserForm Window
Send feedback

Remarks

Allows you to create the windows or dialog boxes in your project. You draw and view controls on a form.

While you are designing a form:

  • Each form window has a Maximize, Minimize, and Close button.

  • You can view the form grid and determine the size of the gridlines from the General tab of the Options dialog box.

  • Use the buttons in the Toolbox to draw controls on the form. You can set your controls to align with the grid of your form from the General tab of the Options dialog box.


Properties (Microsoft Forms)

 Copy code hover
[image]

Properties (Microsoft Forms)
Send feedback

In this section

  • Accelerator Property

  • ActiveControl Property

  • Alignment Property

  • AutoSize Property

  • AutoTab Property

  • AutoWordSelect Property

  • BackColor Property (Microsoft Forms)

  • BackStyle Property (Microsoft Forms)

  • Bold, Italic, Size, StrikeThrough, Underline, Weight Properties

  • BorderColor Property

  • BorderStyle Property

  • BoundColumn Property

  • BoundValue Property

  • Cancel Property (Microsoft Forms)

  • CanPaste Property

  • CanRedo Property

  • CanUndo Property

  • Caption Propert (Microsoft Forms)

  • ClientHeight, ClientLeft, ClientTop, ClientWidth Properties

  • Column Property

  • ColumnCount Property

  • ColumnHeads Property

  • ColumnWidths Property

  • ControlSource Property

  • ControlTipText Property

  • Count Property (Microsoft Forms)

  • CurLine Property

  • CurTargetX Property

  • CurX Property

  • Cycle Property

  • Default Propertyd (Microsoft Forms)

  • Delay Property

  • DragBehavior Property

  • DrawBuffer Property

  • DropButtonStyle Property

  • Enabled Property (Microsoft Forms)

  • EnterFieldBehavior Property

  • EnterKeyBehavior Property

  • ForeColor Property (Microsoft Forms)

  • GroupName Property

  • Height, Width Properties

  • HelpContextID Property

  • HideSelection Property

  • IMEMode Property

  • Index Property (Microsoft Forms)

  • InsideHeight, InsideWidth Properties

  • IntegralHeight Property

  • KeepScrollBarsVisible Property

  • LargeChange Property

  • LayoutEffect Property

  • Left, Top Properties

  • LineCount Property

  • List Property (Microsoft Forms)

  • ListCount Property

  • ListIndex Property

  • ListRows Property

  • ListStyle Property

  • ListWidth Property

  • Locked Property

  • MatchEntry Property

  • MatchFound Property

  • MatchRequired Property

  • Max, Min Properties

  • MaxLength Property

  • MouseIcon Property

  • MousePointer Property

  • MultiLine Property

  • MultiRow Property

  • MultiSelect Property (Microsoft Forms)

  • Name Propertye (Microsoft Forms)

  • Object Property

  • OldHeight, OldWidth Properties

  • OldLeft, OldTop Properties

  • Orientation Property (Microsoft Forms)

  • Parent Propertya (Microsoft Forms)

  • PasswordChar Property

  • Picture Property

  • PictureAlignment Property

  • PicturePosition Property

  • PictureSizeMode Property

  • PictureTiling Property

  • ProportionalThumb Property

  • RightToLeft Property (Microsoft Forms)

  • RowSource Property

  • ScrollBars Property

  • ScrollHeight, ScrollWidth Properties

  • ScrollLeft, ScrollTop Properties

  • Selected Property

  • SelectedItem Property

  • SelectionMargin Property

  • SelLength Property

  • SelStart Property

  • SelText Property

  • ShowDropButtonWhen Property

  • SmallChange Property

  • SpecialEffect Property

  • Style Property

  • TabFixedHeight, TabFixedWidth Properties

  • TabIndex Property

  • TabKeyBehavior Property

  • TabOrientation Property

  • TabStop Property (VBE.Dev)

  • Tag Property

  • TakeFocusOnClick Property

  • Text Property (Microsoft Forms)

  • TextAlign Property

  • TextColumn Property

  • TextLength Property

  • TopIndex Property

  • TransitionEffect Property

  • TransitionPeriod Property

  • TripleState Property

  • Value Property (Microsoft Forms)

  • VerticalScrollbarSide Property

  • Visible Property (Microsoft Forms)

  • WordWrap Property

  • Zoom Property


Accelerator Property

 Copy code hover
[image]

Accelerator Property
Send feedback

Sets or retrieves the accelerator key for a control.

Syntax

object.Accelerator [= String]

The Accelerator property syntax has these parts:

Part | Description
object | Required. A valid object.
String | Optional. The character to use as the accelerator key.

Remarks

To designate an accelerator key, enter a single character for the Accelerator property. You can set Accelerator in the control's property sheet or in code. If the value of this property contains more than one character, the first character in the string becomes the value of Accelerator.

When an accelerator key is used, there is no visual feedback (other than focus) to indicate that the control initiated the Click event. For example, if the accelerator key applies to a CommandButton, the user will not see the button pressed in the interface. The button receives the focus, however, when the user presses the accelerator key.

If the accelerator applies to a Label, the control following the Label in the tab order, rather than the Label itself, receives the focus.


ActiveControl Property

 Copy code hover
[image]

ActiveControl Property
Send feedback

Identifies and allows manipulation of the control that has the focus.

Syntax

object.ActiveControl

The ActiveControl property syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

The ActiveControl property is read-only and is set when you select a control in the interface. You can use ActiveControl as a substitute for the control name when setting properties or calling methods.


Alignment Property

 Copy code hover
[image]

Alignment Property
Send feedback

Specifies the position of a control relative to its caption.

Syntax

object.Alignment [= fmAlignment]

The Alignment property syntax has these parts:

Part | Description
object | Required. A valid object.
fmAlignment | Optional. Caption position.

Settings

The settings for fmAlignment are:

Constant | Value | Description
fmAlignmentLeft | 0 | Places the caption to the left of the control.
fmAlignmentRight | 1 | Places the caption to the right of the control (default).

Remarks

The caption text for a control is left-aligned.

Note Note

Although the Alignment property exists on the ToggleButton, the property is disabled. You cannot set or return a value for this property on the ToggleButton.


AutoSize Property

 Copy code hover
[image]

AutoSize Property
Send feedback

Specifies whether an object automatically resizes to display its entire contents.

Syntax

object.AutoSize [= Boolean]

The AutoSize property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the control is resized.

Settings

The settings for Boolean are:

Value | Description
True | Automatically resizes the control to display its entire contents.
False | Keeps the size of the control constant. Contents are clipped when they exceed the area of the control (default).

Remarks

For controls with captions, the AutoSize property specifies whether the control automatically adjusts to display the entire caption.

For controls without captions, this property specifies whether the control automatically adjusts to display the information stored in the control. In a ComboBox, for example, setting AutoSize to True automatically sets the width of the display area to match the length of the current text.

For a single-line text box, setting AutoSize to True automatically sets the width of the display area to the length of the text in the text box.

For a multiline text box that contains no text, setting AutoSize to True automatically displays the text as a column. The width of the text column is set to accommodate the widest letter of that font size. The height of the text column is set to display the entire text of the TextBox.

For a multiline text box that contains text, setting AutoSize to True automatically enlarges the TextBox vertically to display ithe entire text. The width of the TextBox does not change.

Note Note

If you manually change the size of a control while AutoSize is True, the manual change overrides the size previously set by AutoSize.


AutoTab Property

 Copy code hover
[image]

AutoTab Property
Send feedback

Specifies whether an automatic tab occurs when a user enters the maximum allowable number of characters into a TextBox or the text box portion of a ComboBox.

Syntax

object.AutoTab [= Boolean]

The AutoTab property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Specifies whether an automatic tab occurs.

Settings

The settings for Boolean are:

Value | Description
True | Tab occurs.
False | Tab does not occur (default).

Remarks

The MaxLength property specifies the maximum number of characters allowed in a TextBox or the text box portion of a ComboBox.

You can specify the AutoTab property for a TextBox or ComboBox on a form for which you usually enter a set number of characters. Once a user enters the maximum number of characters, the focus automatically moves to the next control in the tab order. For example, if a TextBox displays inventory stock numbers that are always five characters long, you can use MaxLength to specify the maximum number of characters to enter into the TextBox and AutoTab to automatically tab to the next control after the user enters five characters.

Support for AutoTab varies from one application to another. Not all containers support this property.


AutoWordSelect Property

 Copy code hover
[image]

AutoWordSelect Property
Send feedback

Specifies whether a word or a character is the basic unit used to extend a selection.

Syntax

object.AutoWordSelect [= Boolean]

The AutoWordSelect property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Specifies the basic unit used to extend a selection.

Settings

The settings for Boolean are:

Value | Description
True | Uses a word as the basic unit (default).
False | Uses a character as the basic unit.

Remarks

The AutoWordSelect property specifies how the selection extends or contracts in the edit region of a TextBox or ComboBox.

If the user places the insertion point in the middle of a word and then extends the selection while AutoWordSelect is True, the selection includes the entire word.


BackColor Property (Microsoft Forms)

 Copy code hover
[image]

BackColor Property (Microsoft Forms)
Send feedback

Specifies the background color of the object.

Syntax

object.BackColor [= Long]

The BackColor property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. A value or constant that determines the background color of an object.

Settings

You can use any integer that represents a valid color. You can also specify a color by using the RGB function with red, green, and blue color components. The value of each color component is an integer that ranges from zero to 255. For example, you can specify teal blue as the integer value 4966415 or as red, green, and blue color components 15, 200, 75.

Remarks

You can only see the background color of an object if the BackStyle property is set to fmBackStyleOpaque.


BackStyle Property (Microsoft Forms)

 Copy code hover
[image]

BackStyle Property (Microsoft Forms)
Send feedback

Returns or sets the background style for an object.

Syntax

object.BackStyle [= fmBackStyle]

The BackStyle property syntax has these parts:

Part | Description
object | Required. A valid object.
fmBackStyle | Optional. Specifies the control background.

Settings

The settings for fmBackStyle are:

Constant | Value | Description
fmBackStyleTransparent | 0 | The background is transparent.
fmBackStyleOpaque | 1 | The background is opaque (default).

Remarks

The BackStyle property determines whether a control is transparent. If BackStyle is fmBackStyleOpaque, the control is not transparent and you cannot see anything behind the control on a form. If BackStyle is fmBackStyleTransparent, you can see through the control and look at anything on the form located behind the control.

Note Note

BackStyle does not affect the transparency of bitmaps. You must use a picture editor such as Paintbrush to make a bitmap transparent. Not all controls support transparent bitmaps.


Bold, Italic, Size, StrikeThrough, Underline, Weight Properties

 Copy code hover
[image]

Bold, Italic, Size, StrikeThrough, Underline, Weight Properties
Send feedback

Specifies the visual attributes of text on a displayed or printed form.

Syntax

object.Bold [= Boolean]

object.Italic [= Boolean]

object.Size [= Currency]

object.StrikeThrough [= Boolean]

object.Underline [= Boolean]

object.Weight [= Integer]

The Bold, Italic, Size, StrikeThrough, Underline, and Weight property syntaxes have these parts:

Part | Description
object | Required. A valid object name.
Boolean | Optional. Specifies the font style.
Currency | Optional. A number indicating the font size.
Integer | Optional. Specifies the font style.

The settings for Boolean are:

Value | Description
True | The text has the specified attribute (that is bold, italic, size, strikethrough or underline marks, or weight).
False | The text does not have the specified attribute (default).

The Weight property accepts values from 0 to 1000. A value of zero allows the system to pick the most appropriate weight. A value from 1 to 1000 indicates a specific weight, where 1 represents the lightest type and 1000 represents the darkest type.

Remarks

These properties define the visual characteristics of text. The Bold property determines whether text is normal or bold. The Italic property determines whether text is normal or italic. The Size property determines the height, in points, of displayed text. The Underline property determines whether text is underlined. The StrikeThrough property determines whether the text appears with strikethrough marks. The Weight property determines the darkness of the type.

The font's appearance on screen and in print may differ, depending on your computer and printer. If you select a font that your system can't display with the specified attribute or that isn't installed, the operating system substitutes a similar font. The substitute font will be as similar as possible to the font originally requested.

Changing the value of Bold also changes the value of Weight. Setting Bold to True sets Weight to 700; setting Bold to False sets Weight to 400. Conversely, setting Weight to anything over 550 sets Bold to True; setting Weight to 550 or less sets Bold to False.

The default point size is determined by the operating system.


BorderColor Property

 Copy code hover
[image]

BorderColor Property
Send feedback

Specifies the color of an object's border.

Syntax

object.BorderColor [= Long]

The BorderColor property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. A value or constant that determines the border color of an object.

Settings

You can use any integer that represents a valid color. You can also specify a color by using the RGB function with red, green, and blue color components. The value of each color component is an integer that ranges from zero to 255. For example, you can specify teal blue as the integer value 4966415 or as RGB color component values 15, 200, 75.

Remarks

To use the BorderColor property, the BorderStyle property must be set to a value other than fmBorderStyleNone.

BorderStyle uses BorderColor to define the border colors. The SpecialEffect property uses system colors exclusively to define its border colors. For Windows operating systems, system color settings are part of the Control Panel and are found in the Appearance tab of the Display folder. In Windows NT 4.0 or later, system color settings are stored in the Color folder of the Control Panel.


BorderStyle Property

 Copy code hover
[image]

BorderStyle Property
Send feedback

Specifies the type of border used by a control or a form.

Syntax

object.BorderStyle [= fmBorderStyle]

The BorderStyle property syntax has these parts:

Part | Description
object | Required. A valid object.
fmBorderStyle | Optional. Specifies the border style.

Settings

The settings for fmBorderStyle are:

Constant | Value | Description
fmBorderStyleNone | 0 | The control has no visible border line.
fmBorderStyleSingle | 1 | The control has a single-line border (default).

The default value for a ComboBox, Frame, Label, ListBox or TextBox is 0 (None). The default value for an Image is 1 (Single).

Remarks

For a Frame, the BorderStyle property is ignored if the SpecialEffect property is None.

You can use either BorderStyle or SpecialEffect to specify the border for a control, but not both. If you specify a nonzero value for one of these properties, the system sets the value of the other property to zero. For example, if you set BorderStyle to fmBorderStyleSingle, the system sets SpecialEffect to zero (Flat). If you specify a nonzero value for SpecialEffect, the system sets BorderStyle to zero.

BorderStyle uses BorderColor to define the colors of its borders.


BoundColumn Property

 Copy code hover
[image]

BoundColumn Property
Send feedback

Identifies the source of data in a multicolumn ComboBox or ListBox.

Syntax

object.BoundColumn [= Variant]

The BoundColumn property syntax has these parts:

Part | Description
object | Required. A valid object.
Variant | Optional. Indicates how the BoundColumn value is selected.

Settings

The settings for Variant are:

Value | Description
0 | Assigns the value of the ListIndex property to the control.
1 or greater | Assigns the value from the specified column to the control. Columns are numbered from 1 when using this property (default).

Remarks

When the user chooses a row in a multicolumn ListBox or ComboBox, the BoundColumn property identifies which item from that row to store as the value of the control. For example, if each row contains 8 items and BoundColumn is 3, the system stores the information in the third column of the currently-selected row as the value of the object.

You can display one set of data to users but store different, associated values for the object by using the BoundColumn and the TextColumn properties. TextColumn identifies the column of data displayed in text box portion of a ComboBox and the value stored in the Text property; BoundColumn identifies the column of associated data values stored for the control. For example, you could set up a multicolumn ListBox that contains the names of holidays in one column and dates for the holidays in a second column. To present the holiday names to users, specify the first column as the TextColumn. To store the dates of the holidays, specify the second column as the BoundColumn. To hide the dates of the holidays, set the ColumnWidths property of the sceond column to zero.

If the control is bound to a data source, the value in the column specified by BoundColumn is stored in the data source named in the ControlSource property.

The ListIndex value retrieves the number of the selected row. For example, if you want to know the row of the selected item, set BoundColumn to 0 to assign the number of the selected row as the value of the control. Be sure to retrieve a current value, rather than relying on a previously saved value, if you are referencing a list whose contents might change.

The Column, List, and ListIndex properties all use zero-based numbering. That is, the value of the first item (column or row) is zero; the value of the second item is one, and so on. This means that if BoundColumn is set to 3, you could access the value stored in that column using the expression Column(2).


BoundValue Property

 Copy code hover
[image]

BoundValue Property
Send feedback

Contains the value of a control when that control receives the focus.

Syntax

object.BoundValue [= Variant]

The BoundValue property syntax has these parts:

Part | Description
object | Required. A valid object.
Variant | Optional. The current state or content of the control.

Settings

Control | Description
CheckBox | An integer value indicating whether the item is selected:
 | Null Indicates the item is in a null state, neither selected nor cleared.
 | -1 True. Indicates the item is selected.
 | 0 False. Indicates the item is cleared.
OptionButton | Same as CheckBox.
ToggleButton | Same as CheckBox.
ScrollBar | An integer between the values specified for the Max and Min properties.
SpinButton | Same as ScrollBar.
ComboBox, ListBox | The value in the BoundColumn of the currently selected rows.
CommandButton | Always False.
MultiPage | An integer indicating the currently active page.
 | Zero (0) indicates the first page. The maximum value is one less than the number of pages.
TextBox | The text in the edit region.

Remarks

BoundValue applies to the control that has the focus.

The contents of the BoundValue and Value properties are identical most of the time. When the user edits a control so that its value changes, the contents of BoundValue and Value are different until the change is final.

Several things occur when the user changes the value of a control. For example, if a user changes the text in a TextBox, the following things occur:

  1. The Change event is initiated. At this time the Value property contains the new text and BoundValue contains the previous text.

  2. The BeforeUpdate event is initiated.

  3. The AfterUpdate event is initiated. The values for BoundValue and Value are once again identical, containing the new text.

BoundValue cannot be used with a multi-select list box.


Cancel Property (Microsoft Forms)

 Copy code hover
[image]

Cancel Property (Microsoft Forms)
Send feedback

Returns or sets a value indicating whether a command button is the Cancel button on a form.

Syntax

object.Cancel [= Boolean]

The Cancel property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the object is the Cancel button.

Settings

The settings for Boolean are:

Value | Description
True | The CommandButton is the Cancel button.
False | The CommandButton is not the Cancel button (default).

Remarks

A CommandButton or an object that acts like a command button can be designated as the default command button. For OLE container controls (Windows only), the Cancel property is provided only for those objects that specifically behave as command buttons.

Only one CommandButton on a form can be the Cancel button. Setting Cancel to True for one command button automatically sets it to False for all other objects on the form. When a CommandButton's Cancel property is set to True and the form is the active form, the user can choose the command button by clicking it, pressing ESC, or pressing ENTER when the button has the focus.

A typical use of Cancel is to give the user the option of canceling uncommitted changes and returning the form to its previous state.

You should consider making the Cancel button the default button for forms that support operations that can't be undone (such as delete). To do this, set both Cancel and the Default property to True.


CanPaste Property

 Copy code hover
[image]

CanPaste Property
Send feedback

Specifies whether the Clipboard contains data that the object supports.

Syntax

object.CanPaste

The CanPaste property syntax has these parts:

Part | Description
object | Required. A valid object.

Return Values

The CanPaste property return values are:

Value | Description
True | The object underneath the mouse pointer can receive information pasted from the Clipboard (default).
False | The object underneath the mouse pointer cannot receive information pasted from the Clipboard.

Remarks

CanPaste is read-only.

If the Clipboard data is in a format that the current target object does not support, the CanPaste property is False. For example, if you try to paste a bitmap into an object that only supports text, CanPaste will be False.


CanRedo Property

 Copy code hover
[image]

CanRedo Property
Send feedback

Indicates whether the most recent Undo can be reversed.

Syntax

object.CanRedo

The CanRedo property syntax has these parts:

Part | Description
object | Required. A valid object.

Return Values

The CanRedo property return values are:

Value | Description
True | The most recent Undo can be reversed.
False | The most recent Undo is irreversible.

Remarks

CanRedo is read-only.

To Redo an action means to reverse an Undo; it does not necessarily mean to repeat the last user action.

The following user actions illustrate using Undo and Redo:

  1. Change the setting of an option button.

  2. Enter text into a text box.

  3. Click Undo. The text disappears from the text box.

  4. Click Undo. The option button reverts to its previous setting.

  5. Click Redo. The value of the option button changes.

  6. Click Redo. The text reappears in the text box.


CanUndo Property

 Copy code hover
[image]

CanUndo Property
Send feedback

Indicates whether the last user action can be undone.

Syntax

object.CanUndo

The CanUndo property syntax has these parts:

Part | Description
object | Required. A valid object.

Return Values

The CanUndo property return values are:

Value | Description
True | The most recent user action can be undone.
False | The most recent user action cannot be undone.

Remarks

CanUndo is read-only.

Many user actions can be undone with the Undo command. The CanUndo property indicates whether the most recent action can be undone.


Caption Propert (Microsoft Forms)

 Copy code hover
[image]

Caption Propert (Microsoft Forms)
Send feedback

Descriptive text that appears on an object to identify or describe it.

Syntax

object.Caption [= String]

The Caption property syntax has these parts:

Part | Description
object | Required. A valid object.
String | Optional. A string expression that evaluates to the text displayed as the caption.

Settings

The default setting for a control is a unique name based on the type of control. For example, CommandButton1 is the default caption for the first command button in a form.

Remarks

The text identifies or describes the object with which it is associated. For buttons and labels, the Caption property specifies the text that appears in the control. For Page and Tab objects, it specifies the text that appears on the tab.

If a control's caption is too long, the caption is truncated. If a form's caption is too long for the title bar, the title is displayed with an ellipsis.

The ForeColor property of the control determines the color of the text in the caption.

Tip Tip

If a control has both the Caption and AutoSize properties, setting AutoSize to True automatically adjusts the size of the control to frame the entire caption.


ClientHeight, ClientLeft, ClientTop, ClientWidth Properties

 Copy code hover
[image]

ClientHeight, ClientLeft, ClientTop, ClientWidth Properties
Send feedback

Define the dimensions and location of the display area of a TabStrip.

Syntax

object.ClientHeight [ =Single]

object.ClientLeft [ =Single]

object.ClientTop [ =Single]

object.ClientWidth [ =Single]

The ClientHeight, ClientLeft, ClientTop, and ClientWidth property syntaxes have these parts:

Part | Description
object | Required. A valid object.
Single | Optional. For ClientHeight and ClientWidth, specifies the height or width, in points, of the display area. For ClientLeft and ClientTop, specifies the distance, in points, from the top or left edge of the TabStrip's container.

Remarks

At run time, ClientLeft, ClientTop, ClientHeight, and ClientWidth automatically store the coordinates and dimensions of the TabStrip's internal area, which is shared by objects in the TabStrip.


Column Property

 Copy code hover
[image]

Column Property
Send feedback

Specifies one or more items in a ListBox or ComboBox.

Syntax

object.Column( column, row ) [= Variant]

The Column property syntax has these parts:

Part | Description
object | Required. A valid object.
column | Optional. An integer with a range from 0 to one less than the total number of columns.
row | Optional. An integer with a range from 0 to one less than the total number of rows.
Variant | Optional. Specifies a single value, a column of values, or a two-dimensional array to load into a ListBox or ComboBox.

Settings

If you specify both the column and row values, Column reads or writes a specific item.

If you specify only the column value, the Column property reads or writes the specified column in the current row of the object. For example, MyListBox.Column (3) reads or writes the third column in MyListBox.

Column returns a Variant from the cursor. When a built-in cursor provides the value for Variant (such as when using the AddItem method), the value is a string. When an external cursor provides the value for Variant, formatting associated with the data is not included in the Variant.

Remarks

You can use Column to assign the contents of a combo box or list box to another control, such as a text box. For example, you can set the ControlSource property of a text box to the value in the second column of a list box.

If the user makes no selection when you refer to a column in a combo box or list box, the Column setting is Null. You can check for this condition by using the IsNull function.

You can also use Column to copy an entire two-dimensional array of values to a control. This syntax lets you quickly load a list of choices rather than individually loading each element of the list using AddItem.

Note Note

When copying data from a two-dimensional array, Column transposes the contents of the array in the control so that the contents of ListBox1.Column(X, Y) is the same as MyArray(Y, X). You can also use List to copy an array without transposing it.


ColumnCount Property

 Copy code hover
[image]

ColumnCount Property
Send feedback

Specifies the number of columns to display in a list box or combo box.

Syntax

object.ColumnCount [= Long]

The ColumnCount property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. Specifies the number of columns to display.

Remarks

If you set the ColumnCount property for a list box to 3 on an employee form, one column can list last names, another can list first names, and the third can list employee ID numbers.

Setting ColumnCount to 0 displays zero columns, and setting it to -1 displays all the available columns. For an unbound data source, there is a 10-column limit (0 to 9).

You can use the ColumnWidths property to set the width of the columns displayed in the control.


ColumnHeads Property

 Copy code hover
[image]

ColumnHeads Property
Send feedback

Displays a single row of column headings for list boxes, combo boxes, and objects that accept column headings.

Syntax

object.ColumnHeads [= Boolean]

The ColumnHeads property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Specifies whether the column headings are displayed.

Settings

The settings for Boolean are:

Value | Description
True | Display column headings.
False | Do not display column headings (default).

Headings in combo boxes appear only when the list drops down.

Remarks

When the system uses the first row of data items as column headings, they can't be selected.


ColumnWidths Property

 Copy code hover
[image]

ColumnWidths Property
Send feedback

Specifies the width of each column in a multicolumn combo box or list box.

Syntax

object.ColumnWidths [= String]

The ColumnWidths property syntax has these parts:

Part | Description
object | Required. A valid object.
String | Optional. Sets the column width in points. A setting of -1 or blank results in a calculated width. A width of 0 hides a column. To specify a different unit of measurement, include the unit of measure. A value greater than 0 explicitly specifies the width of the column.

Settings

To separate column entries, use semicolons (;) as list separators. In Windows, use the list separator specified in the Regional Settings section of the Windows Control Panel to change this value.

Any or all of the ColumnWidths property settings can be blank. You create a blank setting by typing a list separator without a preceding value.

If you specify a -1 in the property page, the displayed value in the property page is a blank.

To calculate column widths when ColumnWidths is blank or -1, the width of the control is divided equally among all columns of the list. If the sum of the specified column widths exceeds the width of the control, the list is left-aligned within the control and one or more of the rightmost columns are not displayed. Users can scroll the list using the horizontal scroll bar to display the rightmost columns.

The minimum calculated column width is 72 points (1 inch). To produce columns narrower than this, you must specify the width explicitly.

Unless specified otherwise, column widths are measured in points. To specify another unit of measure, include the units as part of the values. The following examples specify column widths in several units of measure and describe how the various settings would fit in a three-column list box that is 4 inches wide.

Setting | Effect
90;72;90 | The first column is 90 points (1.25 inch); the second column is 72 points (1 inch); the third column is 90 points.
6 cm;0;6 cm | The first column is 6 centimeters; the second column is hidden; the third column is 6 centimeters. Because part of the third column is visible, a horizontal scroll bar appears.
1.5 in;0;2.5 in | The first column is 1.5 inches, the second column is hidden, and the third column is 2.5 inches.
2 in;;2 in | The first column is 2 inches, the second column is 1 inch (default), and the third column is 2 inches. Because only half of the third column is visible, a horizontal scroll bar appears.
(Blank) | All three columns are the same width (1.33 inches).

Remarks

In a combo box, the system displays the column designated by the TextColumn property in the text box portion of the control.


ControlSource Property

 Copy code hover
[image]

ControlSource Property
Send feedback

Identifies the data location used to set or store the Value property of a control. The ControlSource property accepts worksheet ranges from Microsoft Excel.

Syntax

object.ControlSource [= String]

The ControlSource property syntax has these parts:

Part | Description
object | Required. A valid object.
String | Optional. Specifies the worksheet cell linked to the Value property of a control.

Remarks

The ControlSource property identifies a cell or field; it does not contain the data stored in the cell or field. If you change the Value of the control, the change is automatically reflected in the linked cell or field. Similarly, if you change the value of the linked cell or field, the change is automatically reflected in the Value of the control.

You cannot specify another control for the ControlSource. Doing so causes an error.

The default value for ControlSource is an empty string. If ControlSource contains a value other than an empty string, it identifies a linked cell or field. The contents of that cell or field are automatically copied to the Value property when the control is loaded.

Note Note

If the Value property is Null, no value appears in the location identified by ControlSource.


ControlTipText Property

 Copy code hover
[image]

ControlTipText Property
Send feedback

Specifies text that appears when the user briefly holds the mouse pointer over a control without clicking.

Syntax

object.ControlTipText [= String]

The ControlTipText property syntax has these parts:

Part | Description
object | Required. A valid object.
String | Optional. The text that appears when the user holds the mouse pointer over a control.

Remarks

The ControlTipText property lets you give users tips about a control in a running form. The property can be set during design time but only appears by the control during run time.

The default value of ControlTipText is an empty string. When the value of ControlTipText is set to an empty string, no tip is available for that control.


Count Property (Microsoft Forms)

 Copy code hover
[image]

Count Property (Microsoft Forms)
Send feedback

Returns the number of objects in a collection.

Syntax

object.Count

The Count property syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

The Count property is read only.

Note that the index value for the first page or tab of a collection is zero, the value for the second page or tab is one, and so on. For example, if a MultiPage contains two pages, the indexes of the pages are 0 and 1, and the value of Count is 2.


CurLine Property

 Copy code hover
[image]

CurLine Property
Send feedback

Specifies the current line of a control.

Syntax

object.CurLine [= Long]

The CurLine property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. Specifies the current line of a control.

Remarks

The current line of a control is the line that contains the insertion point. The number of the first line is zero.

The CurLine property is valid when the control has the focus.


CurTargetX Property

 Copy code hover
[image]

CurTargetX Property
Send feedback

Retrieves the preferred horizontal position of the insertion point in a multiline TextBox or ComboBox.

Syntax

object.CurTargetX

The CurTargetX property syntax has these parts:

Part | Description
object | Required. A valid object.

Return Values

The CurTargetX property retrieves the preferred position, measured in himetric units. A himetric is 0.0001 meter.

Remarks

The target position is relative to the left edge of the control. If the length of a line is less than the value of the CurTargetX property, you can place the insertion point at the end of the the line. The value of CurTargetX changes when the user sets the insertion point or when the CurX property is set. CurTargetX is read-only.

The return value is valid when the object has focus.

You can use CurTargetX and CurX to move the insertion point as the user scrolls through the contents of a multiline TextBox or ComboBox. When the user moves the insertion point to another line of text by scrolling the content of the object, CurTargetX specifies the preferred position for the insertion point. CurX is set to this value if the line of text is longer than the value of CurTargetX. Otherwise, CurX is set to the end of the line of text.


CurX Property

 Copy code hover
[image]

CurX Property
Send feedback

Specifies the current horizontal position of the insertion point in a multiline TextBox or ComboBox.

Syntax

object.CurX [= Long]

The CurX property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. Indicates the current position, measured in himetrics. A himetric is 0.0001 meter.

Remarks

The CurX property applies to a multiline TextBox or ComboBox. The return value is valid when the object has the focus.

You can use CurTargetX and CurX to position the insertion point as the user scrolls through the contents of a multiline TextBox or ComboBox. When the user moves the insertion point to another line of text by scrolling the content of the object, CurTargetX specifies the preferred position for the insertion point. CurX is set to this value if the line of text is longer than the value of CurTargetX. Otherwise, CurX is set to the end of the line of text.


Cycle Property

 Copy code hover
[image]

Cycle Property
Send feedback

Specifies the action to take when the user leaves the last control on a Frame or Page.

Syntax

object.Cycle [= fmCycle]

The Cycle property syntax has these parts:

Part | Description
object | Required. A valid object.
fmCycle | Optional. Specifies whether cycling includes controls nested in a Frame or MultiPage.

Settings

The settings for fmCycle are:

Constant | Value | Description
fmCycleAllForms | 0 | Cycles through the controls on the form and the controls of the Frame and MultiPage controls that are currently displayed on the form.
fmCycleCurrentForm | 2 | Cycles through the controls on the form, Frame, or MultiPage. The focus stays within the form, Frame, or MultiPage until the focus is explicitly set to a control outside the form, Frame, or MultiPage.

If you specify a non-integer value for Cycle, the value is rounded up to the nearest integer.

Remarks

The tab order identifies the order in which controls receive the focus as the user tabs through a form or subform. The Cycle property determines the action to take when a user tabs from the last control in the tab order.

The fmCycleAllForms setting transfers the focus to the the first control of the next Frame or MultiPage on the form when the user tabs from the last control in the tab order.

The fmCycleCurrentForm setting transfers the focus to the the first control of the same form, Frame, or MultiPage when the user tabs from the last control in the tab order.


Default Propertyd (Microsoft Forms)

 Copy code hover
[image]

Default Propertyd (Microsoft Forms)
Send feedback

Designates the default command button on a form.

Syntax

object.Default [= Boolean]

The Default property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the command button is the default.

Settings

The settings for Boolean are:

Value | Description
True | The CommandButton is the default button.
False | The CommandButton is not the default button (default).

Remarks

A CommandButton or an object that acts like a command button can be designated as the default command button. Only one object on a form can be the default command button. Setting the Default property to True for one object automatically sets it to False for all other objects on the form.

To choose the default command button on an active form, the user can click the button, or press ENTER when no other CommandButton has the focus. Pressing ENTER when no other CommandButton has the focus also initiates the KeyUp event for the default command button.

Default is provided for OLE container controls (Windows only) that specifically act like CommandButton controls.

Tip You should consider making the Cancel button the default button for forms that support operations that can't be undone (such as delete). To do this, set both Default and the Cancel property to True.


Delay Property

 Copy code hover
[image]

Delay Property
Send feedback

Specifies the delay for the SpinUp, SpinDown, and Change events on a SpinButton or ScrollBar.

Syntax

object.Delay [= Long]

The Delay property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. The delay, in milliseconds, between events.

Remarks

The Delay property affects the amount of time between consecutive SpinUp, SpinDown, and Change events generated when the user clicks and holds down a button on a SpinButton or ScrollBar. The first event occurs immediately. The delay to the second occurrence of the event is five times the value of the specified Delay. This initial lag makes it easy to generate a single event rather than a stream of events.

After the initial lag, the interval between events is the value specified for Delay.

The default value of Delay is 50 milliseconds. This means the object initiates the first event after 250 milliseconds (5 times the specified value) and initiates each subsequent event after 50 milliseconds.


DragBehavior Property

 Copy code hover
[image]

DragBehavior Property
Send feedback

Specifies whether the system enables the drag-and-drop feature for a TextBox or ComboBox.

Syntax

object.DragBehavior [= fmDragBehavior]

The DragBehavior property syntax has these parts:

Part | Description
object | Required. A valid object.
fmDragBehavior | Optional. Specifies whether the drag-and-drop feature is enabled.

Settings

The settings for fmDragBehavior are:

Constant | Value | Description
fmDragBehaviorDisabled | 0 | Does not allow a drag-and-drop action (default).
fmDragBehaviorEnabled | 1 | Allows a drag-and-drop action.

Remarks

If the DragBehavior property is enabled, dragging in a text box or combo box starts a drag-and-drop operation on the selected text. If DragBehavior is disabled, dragging in a text box or combo box selects text.

The drop-down portion of a ComboBox does not support drag-and-drop processes, nor does it support selection of list items within the text.

DragBehavior has no effect on a ComboBox whose Style property is set to fmStyleDropDownList.

Note Note

You can combine the effects of the EnterFieldBehavior property and DragBehavior to create a large number of text box styles.


DrawBuffer Property

 Copy code hover
[image]

DrawBuffer Property
Send feedback

Specifies the number of pixels set aside for off-screen memory in rendering a frame.

Syntax

object.DrawBuffer [= value]

Part | Description
object | Required. A valid object name.
value | An integer from 16,000 through 1,048,576 equal to the maximum number of pixels the object can render off-screen.

Remarks

The DrawBuffer property specifies the maximum number of pixels that can be drawn at one time as the display repaints. The actual memory used by the object depends upon the screen resolution of the display. If you set a large value for DrawBuffer, performance will be slower. A large buffer only helps when several large images overlap.

Use the Properties window to specify the value of DrawBuffer.


DropButtonStyle Property

 Copy code hover
[image]

DropButtonStyle Property
Send feedback

Specifies the symbol displayed on the drop button in a ComboBox.

Syntax

object.DropButtonStyle [= fmDropButtonStyle]

The DropButtonStyle property syntax has these parts:

Part | Description
object | Required. A valid object.
fmDropButtonStyle | Optional. The appearance of the drop button.

Settings

The settings for fmDropButtonStyle are:

Constant | Value | Description
fmDropButtonStylePlain | 0 | Displays a plain button, with no symbol.
fmDropButtonStyleArrow | 1 | Displays a down arrow (default).
fmDropButtonStyleEllipsis | 2 | Displays an ellipsis (...).
fmDropButtonStyleReduce | 3 | Displays a horizontal line like an underscore character.

Remarks

The recommended setting for showing items in a list is fmDropButtonStyleArrow. If you want to use the drop button in another way, such as to display a dialog box, specify fmDropButtonStyleEllipsis, fmDropButtonStylePlain, or fmDropButtonStyleReduce and trap the DropButtonClick event.


Enabled Property (Microsoft Forms)

 Copy code hover
[image]

Enabled Property (Microsoft Forms)
Send feedback

Specifies whether a control can receive the focus and respond to user-generated events.

Syntax

object.Enabled [= Boolean]

The Enabled property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the object can respond to user-generated events.

Settings

The settings for Boolean are:

Value | Description
True | The control can receive the focus and respond to user-generated events, and is accessible through code (default).
False | The user cannot interact with the control by using the mouse, keystrokes, accelerators, or hotkeys. The control is generally still accessible through code.

Remarks

Use the Enabled property to enable and disable controls. A disabled control appears dimmed, while an enabled control does not. Also, if a control displays a bitmap, the bitmap is dimmed whenever the control is dimmed. If Enabled is False for an Image, the control does not initiate events but does not appear dimmed.

The Enabled and Locked properties work together to achieve the following effects:

  • If Enabled and Locked are both True, the control can receive focus and appears normally (not dimmed) in the form. The user can copy, but not edit, data in the control.

  • If Enabled is True and Locked is False, the control can receive focus and appears normally in the form. The user can copy and edit data in the control.

  • If Enabled is False and Locked is True, the control cannot receive focus and is dimmed in the form. The user can neither copy nor edit data in the control.

  • If Enabled and Locked are both False, the control cannot receive focus and is dimmed in the form. The user can neither copy nor edit data in the control.

You can combine the settings of the Enabled and the TabStop properties to prevent the user from selecting a command button with TAB, while still allowing the user to click the button. Setting TabStop to False means that the command button won't appear in the tab order. However, if Enabled is True, then the user can still click the command button, as long as TakeFocusOnClick is set to True.

When the user tabs into an enabled MultiPage or TabStrip, the first page or tab in the control receives the focus. If the first page or tab of a MultiPage or TabStrip is disabled, the first enabled page or tab of that control receives the focus. If all pages or tabs of a MultiPage or TabStrip are disabled, the control is disabled and cannot receive the focus.

If a Frame is disabled, all controls it contains are disabled.

Clicking a disabled ListBox does not initiate the Click event.


EnterFieldBehavior Property

 Copy code hover
[image]

EnterFieldBehavior Property
Send feedback

Specifies the selection behavior when entering a TextBox or ComboBox.

Syntax

object.EnterFieldBehavior [= fmEnterFieldBehavior]

The EnterFieldBehavior property syntax has these parts:

Part | Description
object | Required. A valid object.
fmEnterFieldBehavior | Optional. The desired selection behavior.

Settings

The settings for fmEnterFieldBehavior are:

Constant | Value | Description
fmEnterFieldBehaviorSelectAll | 0 | Selects the entire contents of the edit region when entering the control (default).
fmEnterFieldBehaviorRecallSelection | 1 | Leaves the selection unchanged. Visually, this uses the selection that was in effect the last time the control was active.

Remarks

The EnterFieldBehavior property controls the way text is selected when the user tabs to the control, not when the control receives focus as a result of the SetFocus method. Following SetFocus, the contents of the control are not selected and the insertion point appears after the last character in the control's edit region.


EnterKeyBehavior Property

 Copy code hover
[image]

EnterKeyBehavior Property
Send feedback

Defines the effect of pressing ENTER in a TextBox.

Syntax

object.EnterKeyBehavior [= Boolean]

The EnterKeyBehavior property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Specifies the effect of pressing ENTER.

Settings

The settings for Boolean are:

Value | Description
True | Pressing ENTER creates a new line.
False | Pressing ENTER moves the focus to the next object in the tab order (default).

Remarks

The EnterKeyBehavior and MultiLine properties are closely related. The values described above only apply if MultiLine is True. If MultiLine is False, pressing ENTER always moves the focus to the next control in the tab order regardless of the value of EnterKeyBehavior.

The effect of pressing CTRL+ENTER also depends on the value of MultiLine. If MultiLine is True, pressing CTRL+ENTER creates a new line regardless of the value of EnterKeyBehavior. If MultiLine is False, pressing CTRL+ENTER has no effect.


ForeColor Property (Microsoft Forms)

 Copy code hover
[image]

ForeColor Property (Microsoft Forms)
Send feedback

Specifies the foreground color of an object.

Syntax

object.ForeColor [= Long]

The ForeColor property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. A value or constant that determines the foreground color of an object.

Settings

You can use any integer that represents a valid color. You can also specify a color by using the RGB function with red, green, and blue color components. The value of each color component is an integer that ranges from zero to 255. For example, you can specify teal blue as the integer value 4966415 or as red, green, and blue color components 15, 200, 75.

Remarks

Use the ForeColor property for controls on forms to make them easy to read or to convey a special meaning. For example, if a text box reports the number of units in stock, you can change the color of the text when the value falls below the reorder level.

For a ScrollBar or SpinButton, ForeColor sets the color of the arrows. For a Frame, ForeColor changes the color of the caption. For a Font object, ForeColor determines the color of the text.


GroupName Property

 Copy code hover
[image]

GroupName Property
Send feedback

Creates a group of mutually exclusive OptionButton controls.

Syntax

object.GroupName [= String]

The GroupName property syntax has these parts:

Part | Description
object | Required. A valid OptionButton.
String | Optional. The name of the group that includes the OptionButton. Use the same setting for all buttons in the group. The default setting is an empty string.

Remarks

To create a group of mutually exclusive OptionButton controls, you can put the buttons in a Frame on your form, or you can use the GroupName property. GroupName is more efficient for the following reasons:

  • You do not have to include a Frame for each group. By not using a Frame, you reduce the number of controls on the form, and in turn, improve performance and reduce the size of the form.

  • You have more design flexibility. If you use a Frame to create the group, all the buttons must be inside the Frame. If you want more than one group, you must have one Frame for each group. However, if you use GroupName to create the group, the group can include option buttons anywhere on the form. If you want more than one group, specify a unique name for each group; you can still place the individual controls anywhere on the form.

  • You can create buttons with transparent backgrounds, which can improve the visual appearance of your form. The Frame is not a transparent control.

Regardless of which method you use to create the group of buttons, clicking one button in a group sets all other buttons in the same group to False. All option buttons with the same GroupName within a single container are mutually exclusive. You can use the same group name in two containers, but doing so creates two groups (one in each container) rather than one group that includes both containers.

For example, assume your form includes some option buttons and a MultiPage that also includes option buttons. The option buttons on the MultiPage are one group and the buttons on the form are another group. The two groups do not affect each other. Changing the setting of a button on the MultiPage does not affect the buttons on the form.


Height, Width Properties

 Copy code hover
[image]

Height, Width Properties
Send feedback

The height or width, in points, of an object.

Syntax

object.Height [= Single]

object.Width [= Single]

The Height and Width property syntaxes have these parts:

Part | Description
object | Required. A valid object.
Single | Optional. A numeric expression specifying the dimensions of an object.

Remarks

The Height and Width properties are automatically updated when you move or size a control. If you change the size of a control, the Height or Width property stores the new height or width and the OldHeight or OldWidth property stores the previous height or width. If you specify a setting for the Left or Top property that is less than zero, that value will be used to calculate the height or width of the control, but a portion of the control will not be visible on the form.

If you move a control from one part of a form to another, the setting of Height or Width only changes if you size the control as you move it. The settings of the control's Left and Top properties will change to reflect the control's new position relative to the edges of the form that contains it.

The value assigned to Height or Width must be greater than or equal to zero. For most systems, the recommended range of values is from 0 to +32,767. Higher values may also work depending on your system configuration.


HelpContextID Property

 Copy code hover
[image]

HelpContextID Property
Send feedback

The HelpContextID property associates a specific topic in a custom Microsoft Windows Help file with a specific control.

Syntax

object.HelpContextID [= Long]

The HelpContextID property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. A positive integer specifies the context ID of a topic in the Help file associated with the object. Zero indicates no Help topic is associated with the object (default). Must be a valid context ID in the specified Help file.

Remarks

The topic identified by the HelpContextID property is available to users when a form is running. To display the topic, the user must either select the control or set focus to the control, and then press F1.

The HelpContextID property refers to a topic in a custom Help file you have created to describe your form or application. In Visual Basic, the custom Help file is a property of the project.


HideSelection Property

 Copy code hover
[image]

HideSelection Property
Send feedback

Specifies whether selected text remains highlighted when a control does not have the focus.

Syntax

object.HideSelection [= Boolean]

The HideSelection property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the selected text remains highlighted even when the control does not have the focus.

Settings

The settings for Boolean are:

Value | Description
True | Selected text is not highlighted unless the control has the focus (default).
False | Selected text always appears highlighted.

Remarks

You can use the HideSelection property to maintain highlighted text when another form or a dialog box receives the focus, such as in a spell-checking procedure.


IMEMode Property

 Copy code hover
[image]

IMEMode Property
Send feedback

Specifies the default run time mode of the Input Method Editor (IME) for a control. This property applies only to applications written for East Asia and is ignored in other applications.

Syntax

object.IMEMode [= fmIMEMode]

The IMEMode property syntax has these parts:

Part | Description
object | Required. A valid object.
fmIMEMode | Optional. The mode of the Input Method Editor (IME).

Settings

The settings for fmIMEMode are:

Constant | Value | Description
fmIMEModeNoControl | 0 | Does not control IME (default).
fmIMEModeOn | 1 | IME on.
fmIMEModeOff | 2 | IME off. English mode.
fmIMEModeDisable | 3 | IME off. User can't turn on IME by keyboard.
fmIMEModeHiragana | 4 | IME on with Full-width Hiragana mode.
fmIMEModeKatakana | 5 | IME on with Full-width Katakana mode.
fmIMEModeKatakanaHalf | 6 | IME on with Half-width Katakana mode.
fmIMEModeAlphaFull | 7 | IME on with Full-width Alphanumeric mode.
fmIMEModeAlpha | 8 | IME on with Half-width Alphanumeric mode.
fmIMEModeHangulFull | 9 | IME on with Full-width Hangul mode.
fmIMEModeHangul | 10 | IME on with Half-width Hangul mode.

The fmIMEModeNoControl setting indicates that the mode of the IME does not change when the control receives focus at run time. For any other value, the mode of the IME is set to the value specified by the IMEMode property when the control receives focus at run time.

Remarks

There are two ways to set the mode of the IME. One is through the toolbar of the IME. The other is with the IMEMode property of a control, which sets or returns the current mode of the IME. This property allows dynamic control of the IME through code.

The following example explains how IMEMode interacts with the toolbar of the IME. Assume that you have designed a form with TextBox1 and CheckBox1. You have set TextBox1.IMEMode to 0, and you have set CheckBox1.IMEMode to 1. While in design mode you have used the IME toolbar to put the IME in mode 2.

When you run the form, the IME begins in mode 2. If you click TextBox1, the IME mode does not change because IMEMode for this control is 0. If you click CheckBox1, the IME changes to mode 1, because IMEMode for this control is 1. If you click again on TextBox1, the IME remains in mode 1 (IMEMode is 0, so the IME retains its last setting).

However, you can override IMEMode. For example, assume you click CheckBox1 and the IME enters mode 1, as defined by IMEMode for the CheckBox. If you then use the IME toolbar to put the IME in mode 3, then the IME will be set to mode 3 anytime you click the control. This does not change the value of the property, it overrides the property until the next time you run the form.


Index Property (Microsoft Forms)

 Copy code hover
[image]

Index Property (Microsoft Forms)
Send feedback

The position of a Tab object within a Tabs collection or a Page object in a Pages collection.

Syntax

object.Index [= Integer]

The Index property syntax has these parts:

Part | Description
object | Required. A valid object.
Integer | Optional. The index of the currently selected Tab object.

Remarks

The Index property specifies the order in which tabs appear. Changing the value of Index visually changes the order of Pages in a MultiPage or Tabs on a TabStrip. The index value for the first page or tab is zero, the index value of the second page or tab is one, and so on.

In a MultiPage, Index refers to a Page as well as the page's Tab. In a TabStrip, Index refers to the tab only.


InsideHeight, InsideWidth Properties

 Copy code hover
[image]

InsideHeight, InsideWidth Properties
Send feedback

InsideHeight returns the height, in points, of the client region inside a form. InsideWidth returns the width, in points, of the client region inside a form.

Syntax

object.InsideHeight

object.InsideWidth

The InsideHeight and InsideWidth property syntaxes have these parts:

Part | Description
object | Required. A valid object.

Remarks

The InsideHeight and InsideWidth properties are read-only. If the region includes a scroll bar, the returned value does not include the height or width of the scroll bar.


IntegralHeight Property

 Copy code hover
[image]

IntegralHeight Property
Send feedback

Indicates whether a ListBox or TextBox displays full lines of text in a list or partial lines.

Syntax

object.IntegralHeight [= Boolean]

The IntegralHeight property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the list displays partial lines of text.

Settings

The settings for Boolean are:

Value | Description
True | The list resizes itself to display only complete items (default).
False | The list does not resize itself even if the item is too tall to display completely.

Remarks

The IntegralHeight property relates to the height of the list, just as the AutoSize property relates to the width of the list.

If IntegralHeight is True, the list box automatically resizes when necessary to show full rows. If False, the list remains a fixed size; if items are taller than the available space in the list, the entire item is not shown.


KeepScrollBarsVisible Property

 Copy code hover
[image]

KeepScrollBarsVisible Property
Send feedback

Specifies whether scroll bars remain visible when not required.

Syntax

object.KeepScrollBarsVisible [= fmScrollBars]

The KeepScrollBarsVisible property syntax has these parts:

Part | Description
object | Required. A valid object.
fmScrollBars | Optional. Where scroll bars are displayed.

Settings

The settings for fmScrollBars are:

Constant | Value | Description
fmScrollBarsNone | 0 | Displays no scroll bars.
fmScrollBarsHorizontal | 1 | Displays a horizontal scroll bar.
fmScrollBarsVertical | 2 | Displays a vertical scroll bar.
fmScrollBarsBoth | 3 | Displays both a horizontal and a vertical scroll bar (default).

Remarks

If the visible region is large enough to display all the controls on an object such as a Page object or a form, scroll bars are not required. The KeepScrollBarsVisible property determines whether the scroll bars remain visible when they are not required.

If the scroll bars are visible when they are not required, they appear normal in size, and the scroll box fills the entire width or height of the scroll bar.


LargeChange Property

 Copy code hover
[image]

LargeChange Property
Send feedback

Specifies the amount of movement that occurs when the user clicks between the scroll box and scroll arrow.

Syntax

object.LargeChange [= Long]

The LargeChange property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. An integer that specifies the amount of change to the Value property.

Remarks

The LargeChange property applies only to the ScrollBar. It does not apply to the scrollbars in other controls such as a TextBox or a drop-down ComboBox.

The value of LargeChange is the amount by which the ScrollBar's Value property changes when the user clicks the area between the scroll box and scroll arrow. The direction of the movement is always toward the place where the user clicks. For example, in a horizontal ScrollBar, clicking to the left of the scroll box moves the scroll box to the left. In a vertical ScrollBar, clicking above the scroll box moves the scroll box up.

LargeChange does not have units. Any integer is a valid setting for LargeChange. The recommended range of values is from -32,767 to +32,767, and the value must be between the values of the Max and Min properties of the ScrollBar.


LayoutEffect Property

 Copy code hover
[image]

LayoutEffect Property
Send feedback

Specifies whether a control was moved during a layout change.

Syntax

object.LayoutEffect

The LayoutEffect property syntax has these parts:

Part | Description
object | Required. A valid object.

Return Values

The LayoutEffect property return values are:

Constant | Value | Description
fmLayoutEffectNone | 0 | The control was not moved.
fmLayoutEffectInitiate | 1 | The control moved.

Remarks

The LayoutEffect property is read-only and is available only in the Layout event. The Layout event is initiated by the Move method if the Layout argument is True.

The Layout event is not initiated when you change the settings of the Left, Top, Height, or Width properties of a control.

The Layout event sets LayoutEffect for any control that was involved in a move operation. For example, if you move a group of controls, LayoutEffect of each control is set.


Left, Top Properties

 Copy code hover
[image]

Left, Top Properties
Send feedback

The distance between a control and the left or top edge of the form that contains it.

Syntax

object.Left [= Single]

object.Top [= Single]

The Left and Top property syntaxes have these parts:

Part | Description
object | Required. A valid object.
Single | Optional. A numeric expression specifying the coordinates of an object.

Settings

Setting the Left or Top property to 0 places the control's edge at the left or top edge of its container.

Remarks

For most systems, the recommended range of values for Left and Top is from -32,767 to +32,767. Other values may also work depending on your sytem configuration. For a ComboBox, values of Left and Top apply to the text portion of the control, not to the list portion. When you move or size a control, its new Left setting is automatically entered in the property sheet. When you print a form, the control's horizontal or vertical location is determined by its Left or Top setting.


LineCount Property

 Copy code hover
[image]

LineCount Property
Send feedback

Returns the number of text lines in a TextBox or ComboBox.

Syntax

object.LineCount

The LineCount property syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

The LineCount property is read-only.

Note Note

A ComboBox will only have one line.


List Property (Microsoft Forms)

 Copy code hover
[image]

List Property (Microsoft Forms)
Send feedback

Returns or sets the list entries of a ListBox or ComboBox.

Syntax

object.List( row, column ) [= Variant]

The List property syntax has these parts:

Part | Description
object | Required. A valid object.
row | Required. An integer with a range from 0 to one less than the number of entries in the list.
column | Required. An integer with a range from 0 to one less than the number of columns.
Variant | Optional. The contents of the specified entry in the ListBox or ComboBox.

Settings

Row and column numbering begins with zero. That is, the row number of the first row in the list is zero; the column number of the first column is zero. The number of the second row or column is 1, and so on.

Remarks

The List property works with the ListCount and ListIndex properties.Use List to access list items. A list is a variant array; each item in the list has a row number and a column number.

Initially, ComboBox and ListBox contain an empty list.

Note Note

To specify items you want to display in a ComboBox or ListBox, use the AddItem method. To remove items, use the RemoveItem method.

Use List to copy an entire two-dimensional array of values to a control. Use AddItem to load a one-dimensional array or to load an individual element.


ListCount Property

 Copy code hover
[image]

ListCount Property
Send feedback

Returns the number of list entries in a control.

Syntax

object.ListCount

The ListCount property syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

The ListCount property is read-only. ListCount is the number of rows over which you can scroll. ListRows is the maximum to display at once. ListCount is always one greater than the largest value for the ListIndex property, because index numbers begin with 0 and the count of items begins with 1. If no item is selected, ListCount is 0 and ListIndex is -1.


ListIndex Property

 Copy code hover
[image]

ListIndex Property
Send feedback

Identifies the currently selected item in a ListBox or ComboBox.

Syntax

object.ListIndex [= Variant]

The ListIndex property syntax has these parts:

Part | Description
object | Required. A valid object.
Variant | Optional. The currently selected item in the control.

Remarks

The ListIndex property contains an index of the selected row in a list. Values of ListIndex range from -1 to one less than the total number of rows in a list (that is, ListCount - 1). When no rows are selected, ListIndex returns -1. When the user selects a row in a ListBox or ComboBox, the system sets the ListIndex value. The ListIndex value of the first row in a list is 0, the value of the second row is 1, and so on.

Note Note

If you use the MultiSelect property to create a ListBox that allows multiple selections, the Selected property of the ListBox (rather than the ListIndex property) identifies the selected rows. The Selected property is an array with the same number of values as the number of rows in the ListBox. For each row in the list box, Selected is True if the row is selected and False if it is not. In a ListBox that allows multiple selections, ListIndex returns the index of the row that has focus, regardless of whether that row is currently selected.

The ListIndex value is also available by setting the BoundColumn property to 0 for a combo box or list box. If BoundColumn is 0, the underlying data source to which the combo box or list box is bound contains the same list index value as ListIndex.


ListRows Property

 Copy code hover
[image]

ListRows Property
Send feedback

Specifies the maximum number of rows to display in the list.

Syntax

object.ListRows [= Long]

The ListRows property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. An integer indicating the maximum number of rows. The default value is 8.

Remarks

If the number of items in the list exceeds the value of the ListRows property, a scroll bar appears at the right edge of the list box portion of the combo box.


ListStyle Property

 Copy code hover
[image]

ListStyle Property
Send feedback

Specifies the visual appearance of the list in a ListBox or ComboBox.

Syntax

object.ListStyle [= fmListStyle]

The ListStyle property syntax has these parts:

Part | Description
object | Required. A valid object.
fmListStyle | Optional. The visual style of the list.

Settings

The settings for fmListStyle are:

Constant | Value | Description
fmListStylePlain | 0 | Looks like a regular list box, with the background of items highlighted.
fmListStyleOption | 1 | Shows option buttons, or check boxes for a multi-select list (default). When the user selects an item from the group, the option button associated with that item is selected and the option buttons for the other items in the group are deselected.

Remarks

The ListStyle property lets you change the visual presentation of a ListBox or ComboBox. By specifying a setting other than fmListStylePlain, you can present the contents of either control as a group of individual items, with each item including a visual cue to indicate whether it is selected.

If the control supports a single selection (the MultiSelect property is set to fmMultiSelectSingle), the user can press one button in the group. If the control supports multi-select, the user can press two or more buttons in the group.


ListWidth Property

 Copy code hover
[image]

ListWidth Property
Send feedback

Specifies the width of the list in a ComboBox.

Syntax

object.ListWidth [= Variant]

The ListWidth property syntax has these parts:

Part | Description
object | Required. A valid object.
Variant | Optional. The width of the list. A value of zero makes the list as wide as the ComboBox. The default value is to make the list as wide as the text portion of the control.

Remarks

If you want to display a multicolumn list, enter a value that will make the list box wide enough to fit all the columns.


Locked Property

 Copy code hover
[image]

Locked Property
Send feedback

Specifies whether a control can be edited.

Syntax

object.Locked [= Boolean]

The Locked property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the control can be edited.

Settings

The settings for Boolean are:

Value | Description
True | You can't edit the value.
False | You can edit the value (default).

Remarks

When a control is locked and enabled, it can still initiate events and can still receive the focus.


MatchEntry Property

 Copy code hover
[image]

MatchEntry Property
Send feedback

Returns or sets a value indicating how a ListBox or ComboBox searches its list as the user types.

Syntax

object.MatchEntry [= fmMatchEntry]

The MatchEntry property syntax has these parts:

Part | Description
object | Required. A valid object.
fmMatchEntry | Optional. The rule used to match entries in the list.

Settings

The settings for fmMatchEntry are:

Constant | Value | Description
fmMatchEntryFirstLetter | 0 | Basic matching. The control searches for the next entry that starts with the character entered. Repeatedly typing the same letter cycles through all entries beginning with that letter.
FmMatchEntryComplete | 1 | Extended matching. As each character is typed, the control searches for an entry matching all characters entered (default).
FmMatchEntryNone | 2 | No matching.

Remarks

The MatchEntry property searches entries from the TextColumn property of a ListBox or ComboBox.

The control searches the column identified by TextColumn for an entry that matches the user's typed entry. Upon finding a match, the row containing the match is selected, the contents of the column are displayed, and the contents of its BoundColumn property become the value of the control. If the match is unambiguous, finding the match initiates the Click event.

The control initiates the Click event as soon as the user types a sequence of characters that match exactly one entry in the list. As the user types, the entry is compared with the current row in the list and with the next row in the list. When the entry matches only the current row, the match is unambiguous.

In Microsoft Forms, this is true regardless of whether the list is sorted. This means the control finds the first occurrence that matches the entry, based on the order of items in the list. For example, entering either "abc" or "bc" will initiate the Click event for the following list:

Note that in either case, the matched entry is not unique; however, it is sufficiently different from the adjacent entry that the control interprets the match as unambiguous and initiates the Click event.


MatchFound Property

 Copy code hover
[image]

MatchFound Property
Send feedback

Indicates whether the text that a user has typed into a combo box matches any of the entries in the list.

Syntax

object.MatchFound

The MatchFound property syntax has these parts:

Part | Description
object | Required. A valid object.

Return Values

The MatchFound property return values are:

Value | Description
True | The contents of the Value property matches one of the records in the list.
False | The contents of Value does not match any of the records in the list (default).

Remarks

The MatchFound property is read-only. It is not applicable when the MatchEntry property is set to fmMatchEntryNone.


MatchRequired Property

 Copy code hover
[image]

MatchRequired Property
Send feedback

Specifies whether a value entered in the text portion of a ComboBox must match an entry in the existing list portion of the control. The user can enter non-matching values, but may not leave the control until a matching value is entered.

Syntax

object.MatchRequired [= Boolean]

The MatchRequired property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the text entered must match an existing item in the list.

Settings

The settings for Boolean are:

Value | Description
True | The text entered must match an existing list entry.
False | The text entered can be different from all existing list entries (default).

Remarks

If the MatchRequired property is True, the user cannot exit the ComboBox until the text entered matches an entry in the existing list. MatchRequired maintains the integrity of the list by requiring the user to select an existing entry.

Note Note

Not all containers enforce this property.


Max, Min Properties

 Copy code hover
[image]

Max, Min Properties
Send feedback

Specify the maximum and minimum acceptable values for the Value property of a ScrollBar or SpinButton.

Syntax

object.Max [= Long]

object.Min [= Long]

The Max and Min property syntaxes have these parts:

Part | Description
object | Required. A valid object.
Long | Optional. A numeric expression specifying the maximum or minimum Value property setting.

Remarks

Clicking a SpinButton or moving the scroll box in a ScrollBar changes the Value property of the control.

The value for the Max property corresponds to the lowest position of a vertical ScrollBar or the rightmost position of a horizontal ScrollBar. The value for the Min property corresponds to the highest position of a vertical ScrollBar or the leftmost position of a horizontal ScrollBar.

Any integer is an acceptable setting for this property. The recommended range of values is from -32,767 to +32,767. The default value is 1.

Note Note

Min and Max refer to locations, not to relative values, on the ScrollBar. That is, the value of Max could be less than the value of Min. If this is the case, moving toward the Max (bottom) position means decreasing Value; moving toward the Min (top) position means increasing Value.


MaxLength Property

 Copy code hover
[image]

MaxLength Property
Send feedback

Specifies the maximum number of characters a user can enter in a TextBox or ComboBox.

Syntax

object.MaxLength [= Long]

The MaxLength property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. An integer indicating the allowable number of characters.

Remarks

Setting the MaxLength property to 0 indicates there is no limit other than that created by memory constraints.


MouseIcon Property

 Copy code hover
[image]

MouseIcon Property
Send feedback

Assigns a custom icon to an object.

Syntax

object.MouseIcon = LoadPicture( pathname )

The MouseIcon property syntax has these parts:

Part | Description
object | Required. A valid object.
pathname | Required. A string expression specifying the path and filename of the file containing the custom icon.

Remarks

The MouseIcon property is valid when the MousePointer property is set to 99. The mouse icon of an object is the image that appears when the user moves the mouse across that object.

To assign an image for the mouse pointer, you can either assign a picture to the MouseIcon property or load a picture from a file using the LoadPicture function.


MousePointer Property

 Copy code hover
[image]

MousePointer Property
Send feedback

Specifies the type of pointer displayed when the user positions the mouse over a particular object.

Syntax

object.MousePointer [= fmMousePointer]

The MousePointer property syntax has these parts:

Part | Description
object | Required. A valid object.
fmMousePointer | Optional. The shape you want for the mouse pointer.

Settings

The settings for fmMousePointer are:

Constant | Value | Description
fmMousePointerDefault | 0 | Standard pointer. The image is determined by the object (default).
fmMousePointerArrow | 1 | Arrow.
fmMousePointerCross | 2 | Cross-hair pointer.
fmMousePointerIBeam | 3 | I-beam.
fmMousePointerSizeNESW | 6 | Double arrow pointing northeast and southwest.
fmMousePointerSizeNS | 7 | Double arrow pointing north and south.
fmMousePointerSizeNWSE | 8 | Double arrow pointing northwest and southeast.
fmMousePointerSizeWE | 9 | Double arrow pointing west and east.
fmMousePointerUpArrow | 10 | Up arrow.
fmMousePointerHourglass | 11 | Hourglass.
fmMousePointerNoDrop | 12 | "Not" symbol (circle with a diagonal line) on top of the object being dragged. Indicates an invalid drop target.
fmMousePointerAppStarting | 13 | Arrow with an hourglass.
fmMousePointerHelp | 14 | Arrow with a question mark.
fmMousePointerSizeAll | 15 | Size all cursor (arrows pointing north, south, east, and west).
fmMousePointerCustom | 99 | Uses the icon specified by the MouseIcon property.

Remarks

Use the MousePointer property when you want to indicate changes in functionality as the mouse pointer passes over controls on a form. For example, the hourglass setting (11) is useful to indicate that the user must wait for a process or operation to finish.

Some icons vary depending on system settings, such as the icons associated with desktop themes.


MultiLine Property

 Copy code hover
[image]

MultiLine Property
Send feedback

Specifies whether a control can accept and display multiple lines of text.

Syntax

object.MultiLine [= Boolean]

The MultiLine property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the control supports more than one line of text.

Settings

The settings for Boolean are:

Value | Description
True | The text is displayed across multiple lines (default).
False | The text is not displayed across multiple lines.

Remarks

A multiline TextBox allows absolute line breaks and adjusts its quantity of lines to accommodate the amount of text it holds. If needed, a multiline control can have vertical scroll bars.

A single-line TextBox doesn't allow absolute line breaks and doesn't use vertical scroll bars.

Single-line controls ignore the value of the WordWrap property.

Note Note

If you change MultiLine to False in a multiline TextBox, all the characters in the TextBox will be combined into one line, including non-printing characters (such as carriage returns and new-lines).


MultiRow Property

 Copy code hover
[image]

MultiRow Property
Send feedback

Specifies whether the control has more than one row of tabs.

Syntax

object.MultiRow [= Boolean]

The MultiRow property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the control has more than one row of tabs.

Settings

The settings for Boolean are:

Value | Description
True | Allows more than one row of tabs.
False | Restricts tabs to a single row (default).

Remarks

The width and number of tabs determines the number of rows. Changing the control's size also changes the number of rows. This allows the developer to resize the control and ensure that tabs wrap to fit the control. If the MultiRow property is False, then truncation occurs if the width of the tabs exceeds the width of the control.

If MultiRow is False and tabs are truncated, there will be a small scroll bar on the TabStrip to allow scrolling to the other tabs or pages.


MultiSelect Property (Microsoft Forms)

 Copy code hover
[image]

MultiSelect Property (Microsoft Forms)
Send feedback

Indicates whether the object permits multiple selections.

Syntax

object.MultiSelect [= fmMultiSelect]

The MultiSelect property syntax has these parts:

Part | Description
object | Required. A valid object.
fmMultiSelect | Optional. The selection mode that the control uses.

Settings

The settings for fmMultiSelect are:

Constant | Value | Description
fmMultiSelectSingle | 0 | Only one item can be selected (default).
fmMultiSelectMulti | 1 | Pressing the SPACEBAR or clicking selects or deselects an item in the list.
fmMultiSelectExtended | 2 | Pressing SHIFT and clicking the mouse, or pressing SHIFT and one of the arrow keys, extends the selection from the previously selected item to the current item. Pressing CTRL and clicking the mouse selects or deselects an item.

Remarks

When the MultiSelect property is set to Extended or Simple, you must use the list box's Selected property to determine the selected items. Also, the Value property of the control is always Null.

The ListIndex property returns the index of the row with the keyboard focus.


Name Propertye (Microsoft Forms)

 Copy code hover
[image]

Name Propertye (Microsoft Forms)
Send feedback

Specifies the name of a control or an object, or the name of a font to associate with a Font object.

Syntax

For Font
Font.Name [= String]

For all other controls and objects
object.Name [= String]

The Name property syntax has these parts:

Part | Description
object | Required. A valid object.
String | Optional. The name you want to assign to the font or control.

Settings

Guidelines for assigning a string to Name, such as the maximum length of the name, vary from one application to another.

Remarks

For objects, the default value of Name consists of the object's class name followed by an integer. For example, the default name for the first TextBox you place on a form is TextBox1. The default name for the second TextBox is TextBox2.

You can set the Name property for a control from the control's property sheet or, for controls added at run time, by using program statements. If you add a control at design time, you cannot modify its Name property at run time.

Each control added to a form at design time must have a unique name.

For Font objects, Name identifies a particular typeface to use in the text portion of a control, object, or form. The font's appearance on screen and in print may differ, depending on your computer and printer. If you select a font that your system can't display or that isn't installed, the operating system substitutes a similar font.


Object Property

 Copy code hover
[image]

Object Property
Send feedback

Overrides a standard property or method when a new control has a property or method of the same name.

Syntax

object.Object[.property |.method]

The Object property syntax has these parts:

Part | Description
object | Required. The name of an object you have added to the Microsoft Forms Toolbox.
property | Optional. A property that has the same name as a standard Microsoft Forms property.
method | Optional. A method that has the same name as a standard Microsoft Forms method.

Remarks

Object is read-only.

If you add a new control to the Microsoft Forms Toolbox, it is possible that the added control will have a property or method with the same name as a standard Microsoft Forms property or method. The Object property lets you use the property or method from the added control, rather than the standard property or method.


OldHeight, OldWidth Properties

 Copy code hover
[image]

OldHeight, OldWidth Properties
Send feedback

Returns the previous height or width, in points, of the control.

Syntax

object.OldHeight

object.OldWidth

The OldHeight and OldWidth property syntaxes have these parts:

Part | Description
object | Required. A valid object.

Remarks

OldHeight and OldWidth are read-only.

The OldHeight and OldWidth properties are automatically updated when you move or size a control. If you change the size of a control, the Height and Width properties store the new height and OldHeight and OldWidth store the previous height.

These properties are valid only in the Layout event.


OldLeft, OldTop Properties

 Copy code hover
[image]

OldLeft, OldTop Properties
Send feedback

Returns the distance, in points, between the previous position of a control and the left or top edge of the form that contains it.

Syntax

object.OldLeft

object.OldTop

The OldLeft and OldTop property syntaxes have these parts:

Part | Description
object | Required. A valid object.

Remarks

OldLeft and OldTop are read-only.

The OldLeft and OldTop properties are automatically updated when you move or size a control. If you move a control, the Left and Top properties store the new distance from the control to the left edge of its container and OldLeft and OldTop store the previous value of Left.

OldLeft and OldTop are valid only in the Layout event.


Orientation Property (Microsoft Forms)

 Copy code hover
[image]

Orientation Property (Microsoft Forms)
Send feedback

Specifies whether the SpinButton or ScrollBar is oriented vertically or horizontally.

Syntax

object.Orientation [= fmOrientation]

The Orientation property syntax has these parts:

Part | Description
object | Required. A valid object.
fmOrientation | Optional. Orientation of the control.

Settings

The settings for fmOrientation are:

Constant | Value | Description
fmOrientationAuto | -1 | Automatically determines the orientation based upon the dimensions of the control (default).
FmOrientationVertical | 0 | Control is rendered vertically.
FmOrientationHorizontal | 1 | Control is rendered horizontally.

Remarks

If you specify automatic orientation, the height and width of the control determine whether it appears horizontally or vertically. For example, if the control is wider than it is tall, it appears horizontally; if it is taller than it is wide, the control appears vertically.


Parent Propertya (Microsoft Forms)

 Copy code hover
[image]

Parent Propertya (Microsoft Forms)
Send feedback

Returns the name of the form, object, or collection that contains a specific control, object, or collection.

Syntax

object.Parent

The Parent property syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

Parent is read-only.

Use the Parent property to access the properties, methods, or controls of an object's parent.

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


PasswordChar Property

 Copy code hover
[image]

PasswordChar Property
Send feedback

Specifies whether placeholder characters are displayed instead of the characters actually entered in a TextBox.

Syntax

object.PasswordChar [= String]

The PasswordChar property syntax has these parts:

Part | Description
object | Required. A valid object.
String | Optional. A string expression specifying the placeholder character.

Remarks

You can use the PasswordChar property to protect sensitive information, such as passwords or security codes. The value of PasswordChar is the character that appears in a control instead of the actual characters that the user types. If you don't specify a character, the control displays the characters that the user types.


Picture Property

 Copy code hover
[image]

Picture Property
Send feedback

Specifies the bitmap to display on an object.

Syntax

object.Picture = LoadPicture( pathname )

The Picture property syntax has these parts:

Part | Description
object | Required. A valid object.
pathname | Required. The full path to a picture file.

Remarks

While designing a form, you can use the control's property page to assign a bitmap to the Picture property. While running a form, you must use the LoadPicture function to assign a bitmap to Picture.

To remove a picture that is assigned to a control, click the value of the Picture property in the property page and then press DELETE. Pressing BACKSPACE will not remove the picture.

Note Note

For controls with captions, use the PicturePosition property to specify where to display the picture on the object. Use the PictureSizeMode property to determine how the picture fills the object.

Transparent pictures sometimes have a hazy appearance. If you do not like this appearance, display the picture on a control that supports opaque images. Image and MultiPage support opaque images.


PictureAlignment Property

 Copy code hover
[image]

PictureAlignment Property
Send feedback

Specifies the location of a background picture.

Syntax

object.PictureAlignment [= fmPictureAlignment]

The PictureAlignment property syntax has these parts:

Part | Description
object | Required. A valid object.
fmPictureAlignment | Optional. The position where the picture aligns with the control.

Settings

The settings for fmPictureAlignment are:

Constant | Value | Description
fmPictureAlignmentTopLeft | 0 | The top left corner.
fmPictureAlignmentTopRight | 1 | The top right corner.
fmPictureAlignmentCenter | 2 | The center.
fmPictureAlignmentBottomLeft | 3 | The bottom left corner.
fmPictureAlignmentBottomRight | 4 | The bottom right corner.

Remarks

The PictureAlignment property identifies which corner of the picture is the same as the corresponding corner of the control or container where the picture is used.

For example, setting PictureAlignment to fmPictureAlignmentTopLeft means that the top left corner of the picture coincides with the top left corner of the control or container. Setting PictureAlignment to fmPictureAlignmentCenter positions the picture in the middle, relative to the height as well as the width of the control or container.

If you tile an image on a control or container, the setting of PIctureAlignment affects the tiling pattern. For example, if PictureAlignment is set to fmPictureAlignmentUpperLeft, the first copy of the image is laid in the upper left corner of the control or container and additional copies are tiled from left to right across each row. If PictureAlignment is fmPictureAlignmentCenter, the first copy of the image is laid at the center of the control or container, additional copies are laid to the left and right to complete the row, and additional rows are added to fill the control or container.

Note Note

Setting the PictureSizeMode property to fmSizeModeStretch overrides PictureAlignment. When PictureSizeMode is set to fmSizeModeStretch, the picture fills the entire control or container.


PicturePosition Property

 Copy code hover
[image]

PicturePosition Property
Send feedback

Specifies the location of the picture relative to its caption.

Syntax

object.PicturePosition [= fmPicturePosition]

The PicturePosition property syntax has these parts:

Part | Description
object | Required. A valid object.
fmPicturePosition | Optional. How the picture aligns with its container.

Settings

The settings for fmPicturePosition are:

Constant | Value | Description
fmPicturePositionLeftTop | 0 | The picture appears to the left of the caption. The caption is aligned with the top of the picture.
fmPicturePositionLeftCenter | 1 | The picture appears to the left of the caption. The caption is centered relative to the picture.
fmPicturePositionLeftBottom | 2 | The picture appears to the left of the caption. The caption is aligned with the bottom of the picture.
fmPicturePositionRightTop | 3 | The picture appears to the right of the caption. The caption is aligned with the top of the picture.
fmPicturePositionRightCenter | 4 | The picture appears to the right of the caption. The caption is centered relative to the picture.
fmPicturePositionRightBottom | 5 | The picture appears to the right of the caption. The caption is aligned with the bottom of the picture.
fmPicturePositionAboveLeft | 6 | The picture appears above the caption. The caption is aligned with the left edge of the picture.
fmPicturePositionAboveCenter | 7 | The picture appears above the caption. The caption is centered below the picture (default).
fmPicturePositionAboveRight | 8 | The picture appears above the caption. The caption is aligned with the right edge of the picture.
fmPicturePositionBelowLeft | 9 | The picture appears below the caption. The caption is aligned with the left edge of the picture.
fmPicturePositionBelowCenter | 10 | The picture appears below the caption. The caption is centered above the picture.
fmPicturePositionBelowRight | 11 | The picture appears below the caption. The caption is aligned with the right edge of the picture.
fmPicturePositionCenter | 12 | The picture appears in the center of the control. The caption is centered horizontally and vertically on top of the picture.

Remarks

The picture and the caption, as a unit, are centered on the control. If no caption exists, the picture's location is relative to the center of the control.

This property is ignored if the Picture property does not specify a picture.


PictureSizeMode Property

 Copy code hover
[image]

PictureSizeMode Property
Send feedback

Specifies how to display the background picture on a control, form, or page.

Syntax

object.PictureSizeMode [= fmPictureSizeMode]

The PictureSizeMode property syntax has these parts:

Part | Description
object | Required. A valid object.
fmPictureSizeMode | Optional. The action to take if the picture and the form or page that contains it are not the same size.

Settings

The settings for fmPictureSizeMode are:

Constant | Value | Description
fmPictureSizeModeClip | 0 | Crops any part of the picture that is larger than the form or page (default).
fmPictureSizeModeStretch | 1 | Stretches the picture to fill the form or page. This setting distorts the picture in either the horizontal or vertical direction.
fmPictureSizeModeZoom | 3 | Enlarges the picture, but does not distort the picture in either the horizontal or vertical direction.

Remarks

The fmPictureSizeModeClip setting indicates you want to show the picture in its original size and scale. If the form or page is smaller than the picture, this setting only shows the part of the picture that fits within the form or page.

The fmPictureSizeModeStretch and fmPictureSizeModeZoom settings both enlarge the image, but fmPictureSizeModeStretch causes distortion. The fmPictureSizeModeStretch setting enlarges the image horizontally and vertically until the image reaches the corresponding edges of the container or control. The fmPictureSizeModeZoom setting enlarges the image until it reaches either the horizontal or vertical edges of the container or control. If the image reaches the horizontal edges first, any remaining distance to the vertical edges remains blank. If it reaches the vertical edges first, any remaining distance to the horizontal edges remains blank.


PictureTiling Property

 Copy code hover
[image]

PictureTiling Property
Send feedback

Lets you tile a picture in a form or page.

Syntax

object.PictureTiling [= Boolean]

The PictureTiling property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether a picture is repeated across a background.

Settings

The settings for Boolean are:

Value | Description
True | The picture is tiled across the background.
False | The picture is not tiled across the background (default).

Remarks

If a picture is smaller than the form or page that contains it, you can tile the picture on the form or page.

The tiling pattern depends on the current setting of the PictureAlignment and PictureSizeMode properties. For example, if PictureAlignment is set to fmPictureAlignmentTopLeft, the tiling pattern starts at the upper left and repeats the picture across the form or page and down the height of the form or page. If PictureSizeMode is set to fmPictureSizeModeClip, the tiling pattern crops the last tile if it doesn't completely fit on the form or page.


ProportionalThumb Property

 Copy code hover
[image]

ProportionalThumb Property
Send feedback

Specifies whether the size of the scroll box is proportional to the scrolling region or fixed.

Syntax

object.ProportionalThumb [= Boolean]

The ProportionalThumb property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the scroll box is proportional or fixed.

Settings

The settings for Boolean are:

Value | Description
True | The scroll box is proportional in size to the scrolling region (default).
False | The scroll box is a fixed size.

Remarks

The size of a proportional scroll box graphically represents the percentage of the object that is visible in the window. For example, if 75 percent of an object is visible, the scroll box covers three-fourths of the scrolling region in the scroll bar.

If the scroll box is a fixed size, the system determines its size based on the height and width of the scroll bar.


RightToLeft Property (Microsoft Forms)

 Copy code hover
[image]

RightToLeft Property (Microsoft Forms)
Send feedback

Specifies whether a given form supports bidirectional characteristics.

Syntax

expression .RightToLeft [=value]

Remarks

RightToLeft is a new property of the Microsoft Forms 2.0 form that the specified control is placed on; it's not a property of the control. Note, however, that RightToLeft affects both the form and any controls that are placed on it. The following table describes the two possible settings for this property.

Setting | Value
False | 0
True | 1

Microsoft Forms 2.0 controls that have the ability to exhibit bidirectional characteristics do so when the RightToLeft property of the form is set to True. When this property is set to False, forms and controls do not exhibit bidirectional characteristics. Bidirectional features of the RightToLeft property are listed in the following table.

Microsoft Forms 2.0 components

RightToLeft = True behavior

All forms and controls

The vertical scroll bar (if present) is on the left side of the form or control. The initial thumb location of the horizontal scroll bar is the rightmost position, and the rightmost portion of information is displayed.

Form

The title bar caption is right-aligned.

Frame control

The caption is placed in the upper-right corner of the frame.

TabStrip control and MultiPage control

Tabs are displayed in order from right to left for specific TabOrientation settings (that is, the first tab begins at the right boundary of the control).
For TabOrientation = Top, tabs are displayed from right to left along the top edge of the control.
For TabOrientation = Bottom, tabs are displayed from right to left along the bottom edge of the control.

Note Note

If the total width of all tabs exceeds the width of the control and MultiRow = False, tabs are displayed from right to left as if MultiRow = True.

Important note Important

If you add Microsoft Forms 2.0 controls to a container surface that's not a Microsoft Forms 2.0 form (for example, if you add a TabStrip control directly to an Arabic Word document), the control will behave as if the container has a RightToLeft property that's set to False.

Note Note

The VerticalScrollBarSide property described in Help has been replaced by the RightToLeft property described in this topic. Keep in mind that although you can use references to VerticalScrollBarSide in Visual Basic for Applications statements, the property is inoperative.


RowSource Property

 Copy code hover
[image]

RowSource Property
Send feedback

Specifies the source providing a list for a ComboBox or ListBox.

Syntax

object.RowSource [= String]

The RowSource property syntax has these parts:

Part | Description
object | Required. A valid object.
String | Optional. The source of the list for the ComboBox or ListBox.

Remarks

The RowSource property accepts worksheet ranges from Microsoft Excel.


ScrollBars Property

 Copy code hover
[image]

ScrollBars Property
Send feedback

Specifies whether a control, form, or page has vertical scroll bars, horizontal scroll bars, or both.

Syntax

object.ScrollBars [= fmScrollBars]

The ScrollBars property syntax has these parts:

Part | Description
object | Required. A valid object.
fmScrollBars | Optional. Where scroll bars should be displayed.

Settings

The settings for fmScrollBars are:

Constant | Value | Description
fmScrollBarsNone | 0 | Displays no scroll bars (default).
fmScrollBarsHorizontal | 1 | Displays a horizontal scroll bar.
fmScrollBarsVertical | 2 | Displays a vertical scroll bar.
fmScrollBarsBoth | 3 | Displays both a horizontal and a vertical scroll bar.

Remarks

If the KeepScrollBarsVisible property is True, any scroll bar on a form or page is always visible, regardless of whether the object's contents fit within the object's borders.

If visible, a scroll bar constrains its scroll box to the visible region of the scroll bar. It also modifies the scroll position as needed to keep the entire scroll bar visible. The range of a scroll bar changes when the value of the ScrollBars property changes, the scroll size changes, or the visible size changes.

If a scroll bar is not visible, then you can set its scroll position to any value. Negative values and values greater than the scroll size are both valid.

For a single-line control, you can display a horizontal scroll bar by using the ScrollBars and AutoSize properties. Scroll bars are hidden or displayed according to the following rules:

  1. When ScrollBars is set to fmScrollBarsNone, no scroll bar is displayed.

  2. When ScrollBars is set to fmScrollBarsHorizontal or fmScrollBarsBoth, the control displays a horizontal scroll bar if the text is longer than the edit region and if the control has enough room to include the scroll bar underneath its edit region.

  3. When AutoSize is True, the control enlarges itself to accommodate the addition of a scroll bar unless the control is at or near its maximum size.

For a multiline TextBox, you can display scroll bars by using the ScrollBars, WordWrap, and AutoSize properties. Scroll bars are hidden or displayed according to the following rules:

  1. When ScrollBars is set to fmScrollBarsNone, no scroll bar is displayed.

  2. When ScrollBars is set to fmScrollBarsVertical or fmScrollBarsBoth, the control displays a vertical scroll bar if the text is longer than the edit region and if the control has enough room to include the scroll bar at the right edge of its edit region.

  3. When WordWrap is True, the multiline control will not display a horizontal scroll bar. Most multiline controls do not use a horizontal scroll bar.

  4. A multiline control can display a horizontal scroll bar if the following conditions occur simultaneously:

    • The edit region contains a word that is longer than the edit region's width.

    • The control has enabled horizontal scroll bars.

    • The control has enough room to include the scroll bar under the edit region.

    • The WordWrap property is set to False.


ScrollHeight, ScrollWidth Properties

 Copy code hover
[image]

ScrollHeight, ScrollWidth Properties
Send feedback

Specify the height, in points, of the total area that can be viewed by moving the scroll bars on the control, form, or page.

Syntax

object.ScrollHeight [= Single]

object.ScrollWidth [= Single]

The ScrollHeight and ScrollWidth property syntaxes have these parts:

Part | Description
object | Required. A valid object.
Single | Optional. The height or width of the scrollable region.


ScrollLeft, ScrollTop Properties

 Copy code hover
[image]

ScrollLeft, ScrollTop Properties
Send feedback

Specify the distance, in points, of the left or top edge of the visible form from the left or top edge of the logical form, page, or control.

Syntax

object.ScrollLeft [= Single]

object.ScrollTop [= Single]

The ScrollLeft and ScrollTop property syntaxes have these parts:

Part | Description
object | Required. A valid object.
Single | Optional. The distance from the edge of the form.

Remarks

The minimum value is zero; the maximum value is the difference between the value of the ScrollWidth property and the value of the Width property for the form or page.


Selected Property

 Copy code hover
[image]

Selected Property
Send feedback

Returns or sets the selection state of items in a ListBox.

Syntax

object.Selected( index ) [= Boolean]

The Selected property syntax has these parts:

Part | Description
object | Required. A valid object.
index | Required. An integer with a range from 0 to one less than the number of items in the list.
Boolean | Optional. Whether an item is selected.

Settings

The settings for Boolean are:

Value | Description
True | The item is selected.
False | The item is not selected.

Remarks

The Selected property is useful when users can make multiple selections. You can use this property to determine the selected rows in a multi-select list box. You can also use this property to select or deselect rows in a list from code.

The default value of this property is based on the current selection state of the ListBox.

For single-selection list boxes, the Value or ListIndex properties are recommended for getting and setting the selection. In this case, ListIndex returns the index of the selected item. However, in a multiple selection, ListIndex returns the index of the row contained within the focus rectangle, regardless of whether the row is actually selected.

When a list box control's MultiSelect property is set to None, only one row can have its Selected property set to True.

Entering a value that is out of range for the index does not generate an error message, but does not set a property for any item in the list.


SelectedItem Property

 Copy code hover
[image]

SelectedItem Property
Send feedback

Returns the currently selected Tab or Page object.

Syntax

object.SelectedItem

The SelectedItem property syntax has these parts:

Part | Description
object | Required. A valid TabStrip or MultiPage.

Remarks

The SelectedItem property is read-only. Use SelectedItem to programmatically control the currently selected Tab or Page object. For example, you can use SelectedItem to assign values to properties of a Tab or Page object.


SelectionMargin Property

 Copy code hover
[image]

SelectionMargin Property
Send feedback

Specifies whether the user can select a line of text by clicking in the region to the left of the text.

Syntax

object.SelectionMargin [= Boolean]

The SelectionMargin property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether clicking in the margin selects a line of text.

Settings

The settings for Boolean are:

Value | Description
True | Clicking in margin causes selection of text (default).
False | Clicking in margin does not cause selection of text.

Remarks

When the SelectionMargin property is True, the selection margin occupies a thin strip along the left edge of a control's edit region. When set to False, the entire edit region can store text.

If the SelectionMargin property is set to True when a control is printed, the selection margin also prints.


SelLength Property

 Copy code hover
[image]

SelLength Property
Send feedback

The number of characters selected in a text box or the text portion of a combo box.

Syntax

object.SelLength [= Long]

The SelLength property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. A numeric expression specifying the number of characters selected. For SelLength and SelStart, the valid range of settings is 0 to the total number of characters in the edit area of a ComboBox or TextBox.

Remarks

The SelLength property is always valid, even when the control does not have focus. Setting SelLength to a value less than zero creates an error. Attempting to set SelLength to a value greater than the number of characters available in a control results in a value equal to the number of characters in the control.

Note Note

Changing the value of the SelStart property cancels any existing selection in the control, places an insertion point in the text, and sets SelLength to zero.

The default value, zero, means that no text is currently selected.


SelStart Property

 Copy code hover
[image]

SelStart Property
Send feedback

Indicates the starting point of selected text, or the insertion point if no text is selected.

Syntax

object.SelStart [= Long]

The SelStart property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. A numeric expression specifying the starting point of text selected. For SelLength and SelStart, the valid range of settings is 0 to the total number of characters in the edit area of a ComboBox or TextBox. The default value is zero.

Remarks

The SelStart property is always valid, even when the control does not have focus. Setting SelStart to a value less than zero creates an error. Attempting to set SelStart to a value greater than the number of characters available in a control results in a value equal to the number of characters in the control.

Changing the value of SelStart cancels any existing selection in the control, places an insertion point in the text, and sets the SelLength property to zero.


SelText Property

 Copy code hover
[image]

SelText Property
Send feedback

Returns or sets the selected text of a control.

Syntax

object.SelText [= String]

The SelText property syntax has these parts:

Part | Description
object | Required. A valid object.
String | Optional. A string expression containing the selected text.

Remarks

If no characters are selected in the edit region of the control, the SelText property returns a zero length string. This property is valid regardless of whether the control has the focus.


ShowDropButtonWhen Property

 Copy code hover
[image]

ShowDropButtonWhen Property
Send feedback

Specifies when to show the drop-down button for a ComboBox or TextBox.

Syntax

object.ShowDropButtonWhen [= fmShowDropButtonWhen]

The ShowDropButtonWhen property syntax has these parts:

Part | Description
object | Required. A valid object.
fmShowDropButtonWhen | Optional. The circumstances under which the drop-down button will be visible.

Settings

The settings for fmShowDropButtonWhen are:

Constant | Value | Description
fmShowDropButtonWhenNever | 0 | Do not show the drop-down button under any circumstances.
fmShowDropButtonWhenFocus | 1 | Show the drop-down button when the control has the focus.
fmShowDropButtonWhenAlways | 2 | Always show the drop-down button.

For a ComboBox, the default value is fmShowDropButtonWhenAlways; for a TextBox, the default value is fmShowDropButtonWhenNever.


SmallChange Property

 Copy code hover
[image]

SmallChange Property
Send feedback

Specifies the amount of movement that occurs when the user clicks either scroll arrow in a ScrollBar or SpinButton.

Syntax

object.SmallChange [= Long]

The SmallChange property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. An integer that specifies the amount of change to the Value property.

Remarks

The SmallChange property does not have units.

Any integer is an acceptable setting for this property. The recommended range of values is from -32,767 to +32,767. The default value is 1.


SpecialEffect Property

 Copy code hover
[image]

SpecialEffect Property
Send feedback

Specifies the visual appearance of an object.

Syntax

For CheckBox, OptionButton, ToggleButton
object.SpecialEffect [= fmButtonEffect]

For other controls
object.SpecialEffect [= fmSpecialEffect]

The SpecialEffect property syntax has these parts:

Part | Description
object | Required. A valid object.
fmButtonEffect | Optional. The desired visual appearance for a CheckBox, OptionButton, or ToggleButton.
fmSpecialEffect | Optional. The desired visual appearance of an object other than a CheckBox, OptionButton, or ToggleButton.

Settings

The settings for fmSpecialEffect are:

Constant | Value | Description
fmSpecialEffectFlat | 0 | Object appears flat, distinguished from the surrounding form by a border, a change of color, or both. Default for Image and Label, valid for all controls.
fmSpecialEffectRaised | 1 | Object has a highlight on the top and left and a shadow on the bottom and right. Not valid for check boxes or option buttons.
fmSpecialEffectSunken | 2 | Object has a shadow on the top and left and a highlight on the bottom and right. The control and its border appear to be carved into the form that contains them. Default for CheckBox and OptionButton, valid for all controls (default).
fmSpecialEffectEtched | 3 | Border appears to be carved around the edge of the control. Not valid for check boxes or option buttons.
fmSpecialEffectBump | 6 | Object has a ridge on the bottom and right and appears flat on the top and left. Not valid for check boxes or option buttons.

For a Frame, the default value is Sunken.

Note that only Flat and Sunken (0 and 2) are acceptable values for CheckBox, OptionButton, and ToggleButton. All values listed are acceptable for other controls.

Remarks

You can use either the SpecialEffect or the BorderStyle property to specify the edging for a control, but not both. If you specify a nonzero value for one of these properties, the system sets the value of the other property to zero. For example, if you set SpecialEffect to fmSpecialEffectRaised, the system sets BorderStyle to zero (fmBorderStyleNone).

For a Frame, BorderStyle is ignored if SpecialEffect is fmSpecialEffectFlat.

SpecialEffect uses the system colors to define its borders.

Note Note

Although the SpecialEffect property exists on the ToggleButton, the property is disabled. You cannot set or return a value for this property on the ToggleButton.


Style Property

 Copy code hover
[image]

Style Property
Send feedback

For ComboBox, specifies how the user can choose or set the control's value. For MultiPage and TabStrip, identifies the style of the tabs on the control.

Syntax

For ComboBox
object.Style [= fmStyle]

For MultiPage and TabStrip
object.Style [= fmTabStyle]

The Style property syntax has these parts:

Part | Description
object | Required. A valid object.
fmStyle | Optional. Specifies how a user sets the value of a ComboBox.
fmTabStyle | Optional. Specifies the tab style in a MultiPage or TabStrip.

Settings

The settings for fmStyle are:

Constant | Value | Description
fmStyleDropDownCombo | 0 | The ComboBox behaves as a drop-down combo box. The user can type a value in the edit region or select a value from the drop-down list (default).
fmStyleDropDownList | 2 | The ComboBox behaves as a list box. The user must choose a value from the list.

The settings for fmTabStyle are:

Constant | Value | Description
fmTabStyleTabs | 0 | Displays tabs on the tab bar (default).
fmTabStyleButtons | 1 | Displays buttons on the tab bar.
fmTabStyleNone | 2 | Does not display the tab bar.


TabFixedHeight, TabFixedWidth Properties

 Copy code hover
[image]

TabFixedHeight, TabFixedWidth Properties
Send feedback

Sets or returns the fixed height or width of the tabs in points.

Syntax

object.TabFixedHeight [= Single]

object.TabFixedWidth [= Single]

The TabFixedHeight and TabFixedWidth property syntaxes have these parts:

Part | Description
object | Required. A valid object.
Single | Optional. The number of points of the height or width of the tabs on a TabStrip or MultiPage.

Settings

If the value is 0, tab widths are automatically adjusted so that each tab is wide enough to accommodate its contents and each row of tabs spans the width of the control.

If the value is greater than 0, all tabs have an identical width as specified by this property.

Remarks

The minimum size is 4 points.


TabIndex Property

 Copy code hover
[image]

TabIndex Property
Send feedback

Specifies the position of a single object in the form's tab order.

Syntax

object.TabIndex [= Integer]

The TabIndex property syntax has these parts:

Part | Description
object | Required. A valid object.
Integer | Optional. An integer from 0 to one less than the number of controls on the form that have a TabIndex property. Assigning a TabIndex value of less than 0 generates an error. If you assign a TabIndex value greater than the largest index value, the system resets the value to the maximum allowable value.

Remarks

The index value of the first object in the tab order is zero.


TabKeyBehavior Property

 Copy code hover
[image]

TabKeyBehavior Property
Send feedback

Determines whether tabs are allowed in the edit region.

Syntax

object.TabKeyBehavior [= Boolean]

The TabKeyBehavior property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. The effect of pressing TAB.

Settings

The settings for Boolean are:

Value | Description
True | Pressing TAB inserts a tab character in the edit region.
False | Pressing TAB moves the focus to the next object in the tab order (default).

Remarks

The TabKeyBehavior and MultiLine properties are closely related. The values described above only apply if MultiLine is True. If MultiLine is False, pressing TAB always moves the focus to the next control in the tab order regardless of the value of TabKeyBehavior.

The effect of pressing CTRL+TAB also depends on the value of MultiLine. If MultiLine is True, pressing CTRL+TAB creates a new line regardless of the value of TabKeyBehavior. If MultiLine is False, pressing CTRL+TAB has no effect.


TabOrientation Property

 Copy code hover
[image]

TabOrientation Property
Send feedback

Specifies the location of the tabs on a MultiPage or TabStrip.

Syntax

object.TabOrientation [= fmTabOrientation]

The TabOrientation property syntax has these parts:

Part | Description
object | Required. A valid object.
fmTabOrientation | Optional. Where the tabs will appear.

Settings

The settings for fmTabOrientation are:

Constant | Value | Description
fmTabOrientationTop | 0 | The tabs appear at the top of the control (default).
fmTabOrientationBottom | 1 | The tabs appear at the bottom of the control.
fmTabOrientationLeft | 2 | The tabs appear at the left side of the control.
fmTabOrientationRight | 3 | The tabs appear at the right side of the control.

Remarks

If you use TrueType fonts, the text rotates when the TabOrientation property is set to fmTabOrientationLeft or fmTabOrientationRight. If you use bitmapped fonts, the text does not rotate.


TabStop Property (VBE.Dev)

 Copy code hover
[image]

TabStop Property (VBE.Dev)
Send feedback

Indicates whether an object can receive focus when the user tabs to it.

Syntax

object.TabStop [= Boolean]

The TabStop property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the object is a tab stop.

Settings

The settings for Boolean are:

Value | Description
True | Designates the object as a tab stop (default).
False | Bypasses the object when the user is tabbing, although the object still holds its place in the actual tab order, as determined by the TabIndex property.


Tag Property

 Copy code hover
[image]

Tag Property
Send feedback

Stores additional information about an object.

Syntax

object.Tag [= String]

The Tag property syntax has these parts:

Part | Description
object | Required. A valid object.
String | Optional. A string expression identifying the object. The default is a zero-length string ("").

Remarks

Use the Tag property to assign an identification string to an object without affecting other property settings or attributes.

For example, you can use Tag to check the identity of a form or control that is passed as a variable to a procedure.


TakeFocusOnClick Property

 Copy code hover
[image]

TakeFocusOnClick Property
Send feedback

Specifies whether a control takes the focus when clicked.

Syntax

object.TakeFocusOnClick [= Boolean]

The TakeFocusOnClick property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Specifies whether a control takes the focus when clicked.

Settings

The settings for Boolean are:

Value | Description
True | The button takes the focus when clicked (default).
False | The button does not take the focus when clicked.

Remarks

The TakeFocusOnClick property defines only what happens when the user clicks a control. If the user tabs to the control, the control takes the focus regardless of the value of TakeFocusOnClick.

Use this property to complete actions that affect a control without requiring that control to give up focus. For example, assume your form includes a TextBox and a CommandButton that checks for correct spelling of text. You would like to be able to select text in the TextBox, then click the CommandButton and run the spelling checker without taking focus away from the TextBox. You can do this by setting the TakeFocusOnClick property of the CommandButton to False.


Text Property (Microsoft Forms)

 Copy code hover
[image]

Text Property (Microsoft Forms)
Send feedback

Returns or sets the text in a TextBox. Changes the selected row in a ComboBox or ListBox.

Syntax

object.Text [= String]

The Text property syntax has these parts:

Part | Description
object | Required. A valid object.
String | Optional. A string expression specifying text. The default value is a zero-length string ("").

Remarks

For a TextBox, any value you assign to the Text property is also assigned to the Value property.

For a ComboBox, you can use Text to update the value of the control. If the value of Text matches an existing list entry, the value of the ListIndex property (the index of the current row) is set to the row that matches Text. If the value of Text does not match a row, ListIndex is set to -1.

For a ListBox, the value of Text must match an existing list entry. Specifying a value that does not match an existing list entry causes an error.

You cannot use Text to change the value of an entry in a ComboBox or ListBox; use the Column or List property for this purpose.

The ForeColor property determines the color of the text.


TextAlign Property

 Copy code hover
[image]

TextAlign Property
Send feedback

Specifies how text is aligned in a control.

Syntax

object.TextAlign [= fmTextAlign]

The TextAlign property syntax has these parts:

Part | Description
object | Required. A valid object.
fmTextAlign | Optional. How text is aligned in the control.

Settings

The settings for fmTextAlign are:

Constant | Value | Description
fmTextAlignLeft | 1 | Aligns the first character of displayed text with the left edge of the control's display or edit area (default).
fmTextAlignCenter | 2 | Centers the text in the control's display or edit area.
fmTextAlignRight | 3 | Aligns the last character of displayed text with the right edge of the control's display or edit area.

Remarks

For a ComboBox, the TextAlign property only affects the edit region; this property has no effect on the alignment of text in the list. For stand-alone labels, TextAlign determines the alignment of the label's caption.


TextColumn Property

 Copy code hover
[image]

TextColumn Property
Send feedback

Identifies the column in a ComboBox or ListBox to store in the Text property when the user selects a row.

Syntax

object.TextColumn [= Variant]

The TextColumn property syntax has these parts:

Part | Description
object | Required. A valid object.
Variant | Optional. The column to be displayed.

Settings

Values for the TextColumn property range from -1 to the number of columns in the list. The TextColumn value for the first column is 1, the value of the second column is 2, and so on. Setting TextColumn to 0 displays the ListIndex values. Setting TextColumn to -1 displays the first column that has a ColumnWidths value greater than 0.

Remarks

In a combo box, the system displays the column designated by the TextColumn property in the text box portion of the control.

When the user selects a row from a ComboBox or ListBox, the column referenced by TextColumn is stored in the Text property.For example, you could set up a multicolumn ListBox that contains the names of holidays in one column and dates for the holidays in a second column. To present the holiday names to users, specify the first column as the TextColumn. To store the dates of the holidays, specify the second column as the BoundColumn. To hide the dates of the holidays, set the ColumnWidths property of the sceond column to zero.

When the Text property of a ComboBox changes (such as when a user types an entry into the control), the new text is compared to the column of data specified by TextColumn.


TextLength Property

 Copy code hover
[image]

TextLength Property
Send feedback

Returns the length, in characters, of text in the edit region of a TextBox or ComboBox.

Syntax

object.TextLength

The TextLength property syntax has these parts:

Part | Description
object | Required. A valid object.

Remarks

The TextLength property is read-only. For a multiline TextBox, TextLength includes LF (line feed) and CR (carriage return) characters.


TopIndex Property

 Copy code hover
[image]

TopIndex Property
Send feedback

Sets and returns the item that appears in the topmost position in the list.

Syntax

object.TopIndex [= Variant]

The TopIndex property syntax has these parts:

Part | Description
object | Required. A valid object.
Variant | Optional. The number of the list item that is displayed in the topmost position. The default is 0, or the first item in the list.

Settings

Returns the value -1 if the list is empty or not displayed.


TransitionEffect Property

 Copy code hover
[image]

TransitionEffect Property
Send feedback

Specifies the visual effect to use when changing from one page to another.

Syntax

object.TransitionEffect [= fmTransitionEffect]

The TransitionEffect property syntax has these parts:

Part | Description
object | Required. A valid object.
fmTransitionEffect | Optional. The transition effect you want between pages.

Settings

The settings for fmTransitionEffect are:

Constant | Value | Description
fmTransitionEffectNone | 0 | No special effect (default).
fmTransitionEffectCoverUp | 1 | The new page covers the old page, moving from the bottom to the top.
fmTransitionEffectCoverRightUp | 2 | The new page covers the old page, moving from the bottom left corner to the top right corner.
fmTransitionEffectCoverRight | 3 | The new page covers the old page, moving from the left edge to the right.
fmTransitionEffectCoverRightDown | 4 | The new page covers the old page, moving from the top left corner to the bottom right corner.
fmTransitionEffectCoverDown | 5 | The new page covers the old page, moving from the top to the bottom.
fmTransitionEffectCoverLeftDown | 6 | The new page covers the old page, moving from the top right corner to the bottom left corner.
fmTransitionEffectCoverLeft | 7 | The new page covers the old page, moving from the right to the left.
fmTransitionEffectCoverLeftUp | 8 | The new page covers the old page, moving from the bottom right corner to the top left corner.
fmTransitionEffectPushUp | 9 | The new page pushes the old page out of view, moving from the bottom to the top.
fmTransitionEffectPushRight | 10 | The new page pushes the old page out of view, moving from the left to the right.
fmTransitionEffectPushDown | 11 | The new page pushes the old page out of view, moving from the top to the bottom.
fmTransitionEffectPushLeft | 12 | The new page pushes the old page out of view, moving from the right to the left.

Remarks

Use the TransitionPeriod property to specify the duration of a transition effect.


TransitionPeriod Property

 Copy code hover
[image]

TransitionPeriod Property
Send feedback

Specifies the duration, in milliseconds, of a transition effect.

Syntax

object.TransitionPeriod [= Long]

The TransitionPeriod property syntax has these parts:

Part | Description
object | Required. A valid object.
Long | Optional. How long it takes to complete the transition from one page to another.

Remarks

Any integer from zero to 10000 is a valid setting for this property. Setting the TransitionPeriod property to zero disables the transition effect; setting TransitionPeriod to 10000 creates a 10-second transition.


TripleState Property

 Copy code hover
[image]

TripleState Property
Send feedback

Determines whether a user can specify, from the user interface, the Null state for a CheckBox or ToggleButton.

Syntax

object.TripleState [= Boolean]

The TripleState property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the control supports the Null state.

Settings

The settings for Boolean are:

Value | Description
True | The button clicks through three states.
False | The button only supports True and False (default).

Remarks

Although the TripleState property exists on the OptionButton, the property is disabled. Regardless of the value of TripleState, you cannot set the control to Null through the user interface.

When the TripleState property is True, a user can choose from the values of Null, True, and False. The null value is displayed as a shaded button.

When TripleState is False, the user can choose either True or False.

A control set to Null does not initiate the Click event.

Regardless of the property setting, the Null value can always be assigned programmatically to a CheckBox or ToggleButton, causing that control to appear shaded.


Value Property (Microsoft Forms)

 Copy code hover
[image]

Value Property (Microsoft Forms)
Send feedback

Specifies the state or content of a given control.

Syntax

object.Value [= Variant]

The Value property syntax has these parts:

Part | Description
object | Required. A valid object.
Variant | Optional. The state or content of the control.

Settings

Control | Description
CheckBox | An integer value indicating whether the item is selected:
 | Null Indicates the item is in a null state, neither selected nor cleared.
 | -1 True. Indicates the item is selected.
 | 0 False. Indicates the item is cleared.
OptionButton | Same as CheckBox.
ToggleButton | Same as CheckBox.
ScrollBar | An integer between the values specified for the Max and Min properties.
SpinButton | Same as ScrollBar.
ComboBox, ListBox | The value in the BoundColumn of the currently selected rows.
CommandButton | Always False.
MultiPage | An integer indicating the currently active page.
 | Zero (0) indicates the first page. The maximum value is one less than the number of pages.
TextBox | The text in the edit region.

Remarks

For a CommandButton, setting the Value property to True in a macro or procedure initiates the button's Click event.

For a ComboBox, changing the contents of Value does not change the value of BoundColumn. To add or delete entries in a ComboBox, you can use the AddItem or RemoveItem method.

Value cannot be used with a multi-select list box.


VerticalScrollbarSide Property

 Copy code hover
[image]

VerticalScrollbarSide Property
Send feedback

Specifies whether a vertical scroll bar appears on the right or left side of a form or page.

Syntax

object.VerticalScrollbarSide [= fmVerticalScrollbarSide]

The VerticalScrollbarSide property syntax has these parts:

Part | Description
object | Required. A valid object.
fmVerticalScrollbarSide | Optional. Where the scroll bar should appear.

Settings

The settings for fmVerticalScrollbarSide are:

Constant | Value | Description
fmVerticalScrollbarSideRight | 0 | Puts the scroll bar on the right side (default).
fmVerticalScrollBarSideLeft | 1 | Puts the scroll bar on the left side.

Remarks

The VerticalScrollBarSide property is is particularly useful if the form will be used in an environment where reading occurs from right to left.


Visible Property (Microsoft Forms)

 Copy code hover
[image]

Visible Property (Microsoft Forms)
Send feedback

Specifies whether an object is visible or hidden.

Syntax

object.Visible [= Boolean]

The Visible property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the object is visible or hidden.

Settings

The settings for Boolean are:

Value | Description
True | Object is visible (default).
False | Object is hidden.

Remarks

Use the Visible property to control access to information without displaying it. For example, you could use the value of a control on a hidden form as the criteria for a query.

All controls are visible at design time.


WordWrap Property

 Copy code hover
[image]

WordWrap Property
Send feedback

Indicates whether the contents of a control automatically wrap at the end of a line.

Syntax

object.WordWrap [= Boolean]

The WordWrap property syntax has these parts:

Part | Description
object | Required. A valid object.
Boolean | Optional. Whether the control expands to fit the text.

Settings

The settings for Boolean are:

Value | Description
True | The text wraps (default).
False | The text does not wrap.

Remarks

For controls that support the MultiLine property as well as the WordWrap property, WordWrap is ignored when MultiLine is False.


Zoom Property

 Copy code hover
[image]

Zoom Property
Send feedback

Specifies how much to change the size of a displayed object.

Syntax

object.Zoom [= Integer]

The Zoom property syntax has these parts:

Part | Description
object | Required. A valid object.
Integer | Optional. The percentage to increase or decrease the displayed image.

Remarks

The value of the Zoom property specifies a percentage of image enlargement or reduction by which an image display should change. Values from 10 to 400 are valid. The value specified is a percentage of the object's original size; thus, a setting of 400 means you want to enlarge the image to four times its original size (or 400 percent), while a setting of 10 means you want to reduce the image to one-tenth of its original size (or 10 percent).


Visual Basic conceptual topics

 Copy code hover
[image]

Visual Basic conceptual topics
Send feedback

In this section

  • 64-Bit Visual Basic for Applications Overview

  • Avoiding Naming Conflicts

  • Calling Procedures with the Same Name

  • Calling Property Procedures

  • Calling Sub and Function Procedures

  • Creating Object Variables

  • Creating Recursive Procedures

  • Declaring Arrays

  • Declaring Constants

  • Declaring Variables

  • Executing code when setting properties

  • Looping Through Code

  • Making Faster For...Next Loops

  • Passing Arguments Efficiently

  • Returning Strings from Functions

  • Understanding Automation

  • Understanding Conditional Compilation

  • Understanding Named Arguments and Optional Arguments

  • Understanding Objects, Properties, Methods, and Events

  • Understanding Parameter Arrays

  • Understanding Scope and Visibility

  • Understanding the Lifetime of Variables

  • Understanding Variants

  • Understanding Visual Basic Syntax

  • Using Arrays

  • Using Constants

  • Using Data Types Efficiently

  • Using Do...Loop Statements

  • Using For Each...Next Statements

  • Using For...Next Statements

  • Using If...Then...Else Statements

  • Using Parentheses in Code

  • Using Select Case Statements

  • Using the Add-In Manager

  • Using With Statements

  • Visual Basic Naming Rules

  • Working Across Applications

  • Writing a Function Procedure

  • Writing a Property Procedure

  • Writing a Sub Procedure

  • Writing Assignment Statements

  • Writing Data to Files

  • Writing Declaration Statements

  • Writing Executable Statements

  • Writing Visual Basic Statements


64-Bit Visual Basic for Applications Overview

 Copy code hover
[image]

64-Bit Visual Basic for Applications Overview
Send feedback

Microsoft Visual Basic for Applications (VBA) is the version of Visual Basic that ships with Microsoft Office. In Microsoft Office 2010, VBA includes language features that enable VBA code to run correctly in both 32-bit and 64-bit environments.

Note Note

By default, Office 2010 installs the 32-bit version. You must explicitly choose to install the 64-bit version during setup.

Running VBA code that was written before the Office 2010 release (VBA version 6 and earlier) on a 64-bit platform can result in errors if the code is not modified to run in 64-bit versions of Office. Errors will result because VBA version 6 and earlier implicitly targets 32-bit platforms and typically contains Declare Statements that call into the Windows API using 32-bit data types for pointers and handles. Because VBA version 6 and earlier does not have a specific data type for pointers or handles, it uses the Long data type, which is a 32-bit 4-byte data type, to reference pointers and handles. Pointers and handles in 64-bit environments are 8-byte 64-bit quantities. These 64-bit quantities cannot be held in 32-bit data types.

Note Note

You only need to modify VBA code if it runs in the 64-bit version of Microsoft Office.

The problem with running legacy VBA code in 64-bit Office is that trying to load 64-bits into a 32-bit data type truncates the 64-bit quantity. This can result in memory overruns, unexpected results in your code, and possible application failure.

To address this problem and enable VBA code to work correctly in both 32-bit and 64-bit environments, several language features have been added to VBA. The table at the bottom of this document summarizes the new VBA language features. Three important additions are the LongPtr type alias, the LongLong data type, and the PtrSafe keyword.

  • LongPtr - VBA now includes a variable type alias: LongPtr. The actual data type that LongPtr resolves to depends on the version of Office that it is running in: LongPtr resolves to Long in 32-bit versions of Office, and LongPtr resolves to LongLong in 64-bit versions of Office. Use LongPtr for pointers and handles.

  • LongLong - The LongLong data type is a signed 64-bit integer that is only available on 64-bit versions of Office. Use LongLong for 64-bit integrals. Conversion functions must be used to explicitly assign LongLong (including LongPtr on 64-bit platforms) to smaller integral types. Implicit conversions of LongLong to smaller integrals are not allowed.

  • PtrSafe - The PtrSafe keyword asserts that a Declare statement is safe to run in 64-bit versions of Office.

All Declare Statements must now include the PtrSafe keyword when running in 64-bit versions of Office. It is important to understand that simply adding the PtrSafe keyword to a Declare statement only signifies the Declare statement explicitly targets 64-bits, all data types within the statement that need to store 64-bits (including return values and parameters) must still be modified to hold 64-bit quantities.

Note Note

Declare statements with the PtrSafe keyword is the recommended syntax. Declare statements that include PtrSafe work correctly in the VBA7 development environment on both 32-bit and 64-bit platforms. To ensure backwards compatibility in VBA7 and earlier use the following construct:

VBA Copy code Copy code
#If Vba7 Then
Declare PtrSafe Sub...
#Else
Declare Sub...
#EndIf

Consider the following Declare statement examples. Running the unmodified Declare statement in 64-bit versions of Office will result in an error indicating the Declare statement does not include the PtrSafe qualifier. The modified VBA example contains the PtrSafe qualifier, but notice that the return value (a pointer to the active window) returns a Long data type. On 64-bit Office, this is incorrect because the pointer needs to be 64-bits. The PtrSafe qualifier tells the compiler the Declare statement is targeting 64-bits, so the statement executes without error. But because the return value has not been updated to a 64-bit data type, the return value is truncated resulting in an incorrect value returned.

Unmodified legacy VBA Declare statement example:

VBA Copy code Copy code
Declare Function GetActiveWindow Lib "user32" () As Long

VBA Declare statement example modified to include the PtrSafe qualifier but still using a 32-bit return value:

VBA Copy code Copy code
Declare PtrSafe Function GetActiveWindow Lib "user32" () As Long

To reiterate, you must modify the Declare statement to include the PtrSafe qualifier and you must update any variables within the statement that need to hold 64-bit quantities so that the variables use 64-bit data types.

VBA Declare statement example modified to include the PtrSafe keyword and updated to use the proper 64-bit (LongPtr) data type:

VBA Copy code Copy code
Declare PtrSafe Function GetActiveWindow Lib "user32" () As LongPtr

In summary, for code to work in 64-bit versions of Office, you need to locate and modify all existing Declare statements to use the PtrSafe qualifier. And you need to locate and modify all data types within these Declare statements that reference handles or pointers to use the new 64-bit compatible LongPtr type alias, and types that need to hold 64-bit integrals with the new LongLong data type. Additionally, you must update any user defined types (UDTs) that contain pointers or handles, and 64-bit integrals to use 64-bit data types and verify all variable assignments are correct to prevent type mismatch errors.

Writing code that works on both 32-bit and 64-bit Office

To write code that can port between both 32-bit and 64-bit versions of Office you only need to use the new LongPtr type alias instead of Long or LongLong for all pointers and handle values. The LongPtr type alias will resolve to the correct Long or LongLong data type depending on which version of Office is running. Note that if you require different logic to execute, for example you need to manipulate 64-bit values in large Microsoft Excel projects you can use the Win64 conditional compilation constant as shown in the following section.

Writing code that works on both Microsoft Office 2010 (32-bit or 64-bit) and previous versions of Office

To write code that can work in both new and older versions of Office you can use a combination of the new VBA7 and Win64 conditional Compiler Constants. The Vba7 conditional compiler constant is used to determine if code is running in version 7 of the VB editor (the VBA version that ships in Office 2010). The Win64 conditional compilation constant is used to determine which version (32-bit or 64-bit) of Office is running.

VBA Copy code Copy code
#if Vba7 then
'  Code is running in the new VBA7 editor
     #if Win64 then
     '  Code is running in 64-bit version of Microsoft Office
     #else
     '  Code is running in 32-bit version of Microsoft Office
     #end if
#else
' Code is running in VBA version 6 or earlier
#end if

#If Vba7 Then
Declare PtrSafe Sub...
#Else
Declare Sub...
#EndIf

Summary of VBA7 Language Updates

The following table summarizes the new VBA language additions and provides an explanation of each:

Name | Type | Description
PtrSafe | Keyword | Asserts that a Declare statement is targeted for 64-bit systems. Required on 64-bits.
LongPtr | Data type | Type alias that maps to Long on 32-bit systems, or LongLong on 64-bit systems.
LongLong | Data type | 8 byte data type that is only available on 64bit systems. Numeric type. Integer numbers in the range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. LongLong is a valid declared type only on 64-bit platforms. Additionally, LongLong may not be implicitly converted to a smaller type (for example, you can't assign a LongLong to a Long.). This is done to prevent inadvertent pointer truncation. Explicit coercions are allowed, so in the example above, you could apply CLng to a LongLong and assign the result to a Long. (Valid on 64-bit platforms only.)
^ | LongLong type-declaration character | Explicitly declares a literal value as a LongLong. Required to declare a LongLong literal that is larger than the maximum Long value (otherwise it will get implicitly converted to double).
CLngPtr | type conversion function | Converts a simple expression to a LongPtr.
CLngLng | type conversion function | Converts a simple expression to a LongLong data type. (Valid on 64-bit platforms only.)
vbLongLong | VarType constant | VarType constant.
DefLngPtr | DefType statement | Sets the default data type for a range of variables as LongPtr.
DefLngLng | DefType statement | Sets the default data type for a range of variables as LongLong.


Avoiding Naming Conflicts

 Copy code hover
[image]

Avoiding Naming Conflicts
Send feedback

A naming conflict occurs when you try to create or use an identifier that was previously defined. In some cases, naming conflicts generate errors such as "Ambiguous name detected" or "" or "Duplicate declaration in current scope". Naming conflicts that go undetected can result in bugs in your code that produce erroneous results, especially if you do not explicitly declare all variables before first use.

You can avoid most naming conflicts by understanding the scoping, private module-level, and public module-level.

A naming conflict can occur when an identifier:

  • Is visible at more than one scoping level.

  • Has two different meanings at the same level.

For example, procedures in separate modules can have the same name. Therefore, you can define a procedure named MySub in modules named Mod1 and Mod2. No conflicts occur if each procedure is called only from other procedures in its own module. However, an error can occur if MySub is called from a third module, and no qualification is provided to distinguish between the two MySub procedures.

Most naming conflicts can be resolved by preceding each identifier with a qualifier that consists of the module name and, if necessary, a project name. For example:

VBA Copy code Copy code
YourProject.YourModule.YourSub MyProject.MyModule.MyVar

The preceding code calls the Sub procedure YourSub and passes MyVar as an argument. You can use any combination of qualifiers to differentiate identical identifiers.

Visual Basic matches each reference to an identifier with the "closest" declaration of a matching identifier. For example, if MyID is declared Public in two modules in a project (Mod1 and Mod2), you can specify the MyID declared in Mod2 without qualification from within Mod2, but you must qualify it as Mod2.MyID to specify it in Mod1. This is also true if Mod2 is in a different but directly referenced project. However, if Mod2 is in an indirectly referenced project, that is, a project referenced by the project you directly reference, references to the Mod2 variable named MyID must always be qualified with the project name. If you reference MyID from a third, directly referenced module, the match is made with the first declaration encountered by searching:

  • Directly referenced projects, in the order that they appear in the References dialog box of the Tools menu.

  • The modules of each project. Note that there is no inherent order to the modules in the project.

You can't reuse names of host-application objects, for example, R1C1 in Microsoft Excel, at different scoping levels.

Tip Tip

Typical errors caused by naming conflicts include ambiguous names, duplicate declarations, undeclared identifiers, and procedures that are not found. By beginning each module with an Option Explicit statement to force explicit declarations of variables before they are used, you can avoid some potential naming conflicts and identifier-related bugs.


Calling Procedures with the Same Name

 Copy code hover
[image]

Calling Procedures with the Same Name
Send feedback

You can call a procedure located in any module in the same project as the active module just as you would call a procedure in the active module. However, if two or more modules contain a procedure with the same name, you must specify a module name in the calling statement, as shown in the following example:

Copy code Copy code
Sub Main()
    Module1.MyProcedure
End Sub

If you give the same name to two different procedures in two different projects, you must specify a project name when you call that procedure. For example, the following procedure calls the Main procedure in the MyModule module in the MyProject.vbp project.

Copy code Copy code
Sub Main()
    [MyProject.vbp].[MyModule].Main
End Sub
Note Note

Different applications have different names for a project. For example, in Microsoft Access, a project is called a database (.mdb); in Microsoft Excel, it's called a workbook (.xls)

Tips for Calling Procedures

  • If you rename a module or project, be sure to change the module or project name wherever it appears in calling statements; otherwise, Visual Basic will not be able to find the called procedure. You can use the Replace command on the Edit menu to find and replace text in a module.

  • To avoid naming conflicts among referenced projects, give your procedures unique names so you can call a procedure without specifying a project or module.


Calling Property Procedures

 Copy code hover
[image]

Calling Property Procedures
Send feedback

The following table lists the syntax for calling property procedures:

Property Procedure | Syntax
Property Let | [object.]propname(arguments)] = argument
Property Get | varname = [object.]propname(arguments)]
Property Set | Set [object.]propname[.(arguments)] = varname

When you call a Property Let or Property Set procedure, one argument always appears on the right side of the equal sign (=).

When you declare a Property Let or Property Set procedure with multiple arguments, Visual Basic passes the argument on the right side of the call to the last argument in the Property Let or Property Set declaration. For example, the following diagram shows how arguments in the Property procedure call relate to arguments in the Property Let declaration:

In practice, the only use for property procedures with multiple arguments is to create arrays of properties.


Calling Sub and Function Procedures

 Copy code hover
[image]

Calling Sub and Function Procedures
Send feedback

To call a Sub procedure from another procedure, type the name of the procedure and include values for any required arguments. The Call statement is not required, but if you use it, you must enclose any arguments in parentheses.

You can use a Sub procedure to organize other procedures so they are easier to understand and debug. In the following example, the Sub procedure Main calls the Sub procedure MultiBeep , passing the value 56 for its argument. After MultiBeep runs, control returns to Main , and Main calls the Sub procedure Message . Message displays a message box; when the user clicks OK, control returns to Main , and calls the Sub procedure MultiBeep , passing the value 56 for its argument. After MultiBeep runs, control returns to Main , and Main calls the Sub procedure Message . Message displays a message box; when the user clicks OK, control returns to Main , and Main finishes.

Copy code Copy code
Sub Main()
 MultiBeep 56
 Message
End Sub

Sub MultiBeep(numbeeps)
 For counter = 1 To numbeeps
 Beep
 Next counter
End Sub

Sub Message()
 MsgBox "Time to take a break!"
End Sub

Calling Sub Procedures with More than One Argument

The following example shows two ways to call a Sub procedure with more than one argument. The second time is called, parentheses are required around the arguments because the Call statement is used.

Copy code Copy code
Sub Main()
 HouseCalc 99800, 43100
 Call HouseCalc(380950, 49500)
End Sub

Sub HouseCalc(price As Single, wage As Single)
 If 2.5 * wage <= 0.8 * price Then
 MsgBox "You cannot afford this house."
 Else
 MsgBox "This house is affordable."
 End If
End Sub

Using Parentheses when Calling Function Procedures

To use the return value of a function, assign the function to a variable and enclose the arguments in parentheses, as shown in the following example.

Copy code Copy code
Answer3 = MsgBox("Are you happy with your salary?", 4, "Question 3")

If you're not interested in the return value of a function, you can call a function the same way you call a Sub procedure. Omit the parentheses, list the arguments, and do not assign the function to a variable, as shown in the following example.

Copy code Copy code
MsgBox "Task Completed!", 0, "Task Box"

If you include parentheses in the preceding example, the statement causes a syntax error.

Passing Named Arguments

A statement in a Sub or Function procedure can pass values to called procedures using named arguments. You can list named arguments in any order. A named argument consists of the name of the argument followed by a colon and an equal sign (:=), and the value assigned to the argument.

The following example calls the MsgBox function using named arguments with no return value.

Copy code Copy code
MsgBox Title:="Task Box", Prompt:="Task Completed!"

The following example calls the MsgBox function using named arguments. The return value is assigned to the variable .

Copy code Copy code
answer3 = MsgBox(Title:="Question 3", _
Prompt:="Are you happy with your salary?", Buttons:=4)


Creating Object Variables

 Copy code hover
[image]

Creating Object Variables
Send feedback

You can treat an object variable exactly the same as the object to which it refers. You can set or return the properties of the object or use any of its methods.

To create an object variable:

  1. Declare the object variable.

  2. Assign the object variable to an object.

Declaring an Object Variable

Use the Dim statement or one of the other declaration statements (Public, Private, or Static) to declare an object variable. A variable that refers to an object must be a Variant, an Object, or a specific type of object. For example, the following declarations are valid:

Copy code Copy code
' Declare MyObject as Variant data type.
Dim MyObject
' Declare MyObject as Object data type.
Dim MyObject As Object
' Declare MyObject as Font type.
Dim MyObject As Font
Note Note

If you use an object variable without declaring it first, the data type of the object variable is Variant by default.

You can declare an object variable with the Object data type when the specific object type is not known until the procedure runs. Use the Object data type to create a generic reference to any object.

If you know the specific object type, you should declare the object variable as that object type. For example, if the application contains a Sample object type, you can declare an object variable for that object using either of these statements:

Copy code Copy code
Dim MyObject As Object ' Declared as generic object.
Dim MyObject As Sample ' Declared only as Sample object.

Declaring specific object types provides automatic type checking, faster code, and improved readability.

Assigning an Object Variable to an Object

Use the Set statement to assign an object to an object variable. You can assign an object expression or Nothing. For example, the following object variable assignments are valid:

Copy code Copy code
Set MyObject = YourObject ' Assign object reference.
Set MyObject = Nothing ' Discontinue association.

You can combine declaring an object variable with assigning an object to it by using the New keyword with the Set statement. For example:

Copy code Copy code
Set MyObject = New Object ' Create and Assign

Setting an object variable equal to Nothing discontinues the association of the object variable with any specific object. This prevents you from accidentally changing the object by changing the variable. An object variable is always set to Nothing after closing the associated object so you can test whether or not the object variable points to a valid object. For example:

Copy code Copy code
If Not MyObject Is Nothing Then
 ' Variable refers to valid object.
 . . .
End If

Of course, this test can never determine with absolute certainty whether or not a user has closed the application containing the object to which the object variable refers.

Referring to the Current Instance of an Object

Use the Me keyword to refer to the current instance of the object where the code is running. All procedures associated with the current object have access to the object referred to as Me. Using Me is particularly useful for passing information about the current instance of an object to a procedure in another module. For example, suppose you have the following procedure in a module:

Copy code Copy code
Sub ChangeObjectColor(MyObjectName As Object)
 MyObjectName.BackColor = RGB(Rnd * 256, Rnd * 256, Rnd * 256)
End Sub

You can call the procedure and pass the current instance of the object as an argument using the following statement:

Copy code Copy code
ChangeObjectColor Me


Creating Recursive Procedures

 Copy code hover
[image]

Creating Recursive Procedures
Send feedback

Procedures have a limited amount of space for variables. Each time a procedure calls itself, more of that space is used. A procedure that calls itself is a recursive procedure. A recursive procedure that continuously calls itself eventually causes an error. For example:

Copy code Copy code
Function RunOut(Maximum)
 RunOut = RunOut(Maximum)
End Function

This error may be less obvious when two procedures call each other indefinitely, or when some condition that limits the recursion is never met. Recursion does have its uses. For example, the following procedure uses a recursive function to calculate factorials:

Copy code Copy code
Function Factorial (N)
 If N <= 1 Then ' Reached end of recursive calls.
 Factorial = 1 ' (N = 0) so climb back out of calls.
 Else ' Call Factorial again if N > 0.
 Factorial = Factorial(N - 1) * N
 End If
End Function

You should test your recursive procedure to make sure it does not call itself so many times that you run out of memory. If you get an error, make sure your procedure is not calling itself indefinitely. After that, try to conserve memory by:

  • Eliminating unnecessary variables.

  • Using data types other than Variant.

  • Re-evaluating the logic of the procedure. You can often substitute nested loops for recursion.


Declaring Arrays

 Copy code hover
[image]

Declaring Arrays
Send feedback

Arrays are declared the same way as other variables, using the Dim, Static, Private, or Public statements. The difference between scalar variables (those that aren't arrays) and array variables is that you generally must specify the size of the array. An array whose size is specified is a fixed-size array. An array whose size can be changed while a program is running is a dynamic array.

Whether an array is indexed from 0 or 1 depends on the setting of the Option Base statement. If Option Base 1 is not specified, all array indexes begin at zero.

Declaring a Fixed Array

In the following line of code, a fixed-size array is declared as an Integer array having 11 rows and 11 columns:

Copy code Copy code
Dim MyArray(10, 10) As Integer

The first argument represents the rows; the second argument represents the columns.

As with any other variable declaration, unless you specify a data type for the array, the data type of the elements in a declared array is Variant. Each numeric Variant element of the array uses 16 bytes. Each string Variant element uses 22 bytes. To write code that is as compact as possible, explicitly declare your arrays to be of a data type other than Variant. The following lines of code compare the size of several arrays:

Copy code Copy code
' Integer array uses 22 bytes (11 elements * 2 bytes).
ReDim MyIntegerArray(10) As Integer

' Double-precision array uses 88 bytes (11 elements * 8 bytes).
ReDim MyDoubleArray(10) As Double

' Variant array uses at least 176 bytes (11 elements * 16 bytes).
ReDim MyVariantArray(10)

' Integer array uses 100 * 100 * 2 bytes (20,000 bytes).
ReDim MyIntegerArray (99, 99) As Integer

' Double-precision array uses 100 * 100 * 8 bytes (80,000 bytes).
ReDim MyDoubleArray (99, 99) As Double

' Variant array uses at least 160,000 bytes (100 * 100 * 16 bytes).
ReDim MyVariantArray(99, 99)

The maximum size of an array varies, based on your operating system and how much memory is available. Using an array that exceeds the amount of RAM available on your system is slower because the data must be read from and written to disk.

Declaring a Dynamic Array

By declaring a dynamic array, you can size the array while the code is running. Use a Static, Dim, Private, or Public statement to declare an array, leaving the parentheses empty, as shown in the following example.

Copy code Copy code
Dim sngArray() As Single
Note Note

You can use the ReDim statement to declare an array implicitly within a procedure. Be careful not to misspell the name of the array when you use the ReDim statement. Even if the Option Explicit statement is included in the module, a second array will be created.

In a procedure within the array's scope, use the ReDim statement to change the number of dimensions, to define the number of elements, and to define the upper and lower bounds for each dimension. You can use the ReDim statement to change the dynamic array as often as necessary. However, each time you do this, the existing values in the array are lost. Use ReDim Preserve to expand an array while preserving existing values in the array. For example, the following statement enlarges the array by 10 elements without losing the current values of the original elements.

Copy code Copy code
ReDim Preserve varArray(UBound(varArray) + 10)
Note Note

When you use the Preserve keyword with a dynamic array, you can change only the upper bound of the last dimension, but you can't change the number of dimensions.


Declaring Constants

 Copy code hover
[image]

Declaring Constants
Send feedback

By declaring a constant, you can assign a meaningful name to a value. You use the Const statement to declare a constant and set its value. After a constant is declared, it cannot be modified or assigned a new value.

You can declare a constant within a procedure or at the top of a module, in the Declarations section. Module-level constants are private by default. To declare a public module-level constant, precede the Const statement with the Public keyword. You can explicitly declare a private constant by preceding the Const statement with the Private keyword to make it easier to read and interpret your code. For more information, see "Understanding Scope and Visibility" in Visual Basic Help.

The following example declares the Public constant conAge as an Integer and assigns it the value as an Integer and assigns it the value 34 .

Copy code Copy code
Public Const conAge As Integer = 34

Constants can be declared as one of the following data types: Boolean, Byte, Integer, Long, Currency, Single, Double, Date, String, or Variant. Because you already know the value of a constant, you can specify the data type in a Const statement. For more information on data types, see "Data Type Summary" in Visual Basic Help.

You can declare several constants in one statement. To specify a data type, you must include the data type for each constant. In the following statement, the constants conAge and and conWage are declared as Integer.

Copy code Copy code
Const conAge As Integer = 34, conWage As Currency = 35000


Declaring Variables

 Copy code hover
[image]

Declaring Variables
Send feedback

When declaring variables, you usually use a Dim statement. A declaration statement can be placed within a procedure to create a procedure-level variable. Or it may be placed at the top of a module, in the Declarations section, to create a module-level variable.

The following example creates the variable and specifies the String data type.

Copy code Copy code
Dim strName As String

If this statement appears within a procedure, the variable strName can be used only in that procedure. If the statement appears in the Declarations section of the module, the variable can be used only in that procedure. If the statement appears in the Declarations section of the module, the variable strName is available to all procedures within the module, but not to procedures in other modules in the project. To make this variable available to all procedures in the project, precede it with the Public statement, as in the following example:

Copy code Copy code
Public strName As String

For information about naming your variables, see "Visual Basic Naming Rules" in Visual Basic Help.

Variables can be declared as one of the following data types: Boolean, Byte, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, or Variant. If you do not specify a data type, the Variant data type is assigned by default. You can also create a user-defined type using the Type statement. For more information on data types, see "Data Type Summary" in Visual Basic Help.

You can declare several variables in one statement. To specify a data type, you must include the data type for each variable. In the following statement, the variables intX , intY , and , intY , and intZ are declared as type Integer.

Copy code Copy code
Dim intX As Integer, intY As Integer, intZ As Integer

In the following statement, intX and intY are declared as type Variant; only and intY are declared as type Variant; only intZ is declared as type Integer.

Copy code Copy code
Dim intX, intY, intZ As Integer

You don't have to supply the variable's data type in the declaration statement. If you omit the data type, the variable will be of type Variant.

Using the Public Statement

You can use the Public statement to declare public module-level variables.

Copy code Copy code
Public strName As String

Public variables can be used in any procedures in the project. If a public variable is declared in a standard module or a class module, it can also be used in any projects that reference the project where the public variable is declared.

Using the Private Statement

You can use the Private statement to declare private module-level variables.

Copy code Copy code
Private MyName As String

Private variables can be used only by procedures in the same module.

Note Note

When used at the module level, the Dim statement is equivalent to the Private statement. You might want to use the Private statement to make your code easier to read and interpret.

Using the Static Statement

When you use the Static statement instead of a Dim statement, the declared variable will retain its value between calls.

Using the Option Explicit Statement

You can implicitly declare a variable in Visual Basic simply by using it in an assignment statement. All variables that are implicitly declared are of type Variant. Variables of type Variant require more memory resources than most other variables. Your application will be more efficient if you declare variables explicitly and with a specific data type. Explicitly declaring all variables reduces the incidence of naming-conflict errors and spelling mistakes.

If you don't want Visual Basic to make implicit declarations, you can place the Option Explicit statement in a module before any procedures. This statement requires you to explicitly declare all variables within the module. If a module includes the Option Explicit statement, a compile-time error will occur when Visual Basic encounters a variable name that has not been previously declared, or that has been spelled incorrectly.

You can set an option in your Visual Basic programming environment to automatically include the Option Explicit statement in all new modules. See your application's documentation for help on how to change Visual Basic environment options. Note that this option does not change existing code you have written.

Note Note

You must explicitly declare fixed arrays and dynamic arrays.

Declaring an Object Variable for Automation

When you use one application to control another application's objects, you should set a reference to the other application's type library. Once you set a reference, you can declare object variables according to their most specific type. For example, if you are in Microsoft Word when you set a reference to the Microsoft Excel type library, you can declare a variable of type Worksheet from within Microsoft Word to represent a Microsoft Excel Worksheet object.

If you are using another application to control Microsoft Access objects, in most cases, you can declare object variables according to their most specific type. You can also use the New keyword to create a new instance of an object automatically. However, you may have to indicate that it is a Microsoft Access object. For example, when you declare an object variable to represent a Microsoft Access form from within Microsoft Visual Basic, you must distinguish the Microsoft Access Form object from a Visual Basic Form object. Include the name of the type library in the variable declaration, as in the following example:

Copy code Copy code
Dim frmOrders As New Access.Form

Some applications don't recognize individual Microsoft Access object types. Even if you set a reference to the Microsoft Access type library from these applications, you must declare all Microsoft Access object variables as type Object. Nor can you use the New keyword to create a new instance of the object. The following example shows how to declare a variable to represent an instance of the Microsoft Access Application object from an application that doesn't recognize Microsoft Access object types. The application then creates an instance of the Application object.

Copy code Copy code
Dim appAccess As Object
Set appAccess = CreateObject("Access.Application")

To determine which syntax an application supports, see the application's documentation.


Executing code when setting properties

 Copy code hover
[image]

Executing code when setting properties
Send feedback

You can create Property Let, Property Set, and Property Get procedures that share the same name. By doing this, you can create a group of related procedures that work together. Once a name is used for a Property procedure, that name can't be used to name a Sub or Function procedure, a variable, or a user-defined type.

The Property Let statement allows you to create a procedure that sets the value of the property. One example might be a Property procedure that creates an inverted property for a bitmap on a form. This is the syntax used to call the Property Let procedure:

Copy code Copy code
Form1.Inverted = True

The actual work of inverting a bitmap on the form is done within the Property Let procedure:

Copy code Copy code
Private IsInverted As Boolean

Property Let Inverted(X As Boolean)
 IsInverted = X
 If IsInverted Then
 …
 (statements)
 Else
 (statements)
 End If
End Property

The form-level variable stores the setting of your property. By declaring it Private, the user can only change it only using your Property Let procedure. Use a name that makes it easy to recognize that the variable is used for the property.

This Property Get procedure is used to return the current state of the property:

Copy code Copy code
Property Get Inverted() As Boolean
 Inverted = IsInverted
End Property

Property procedures make it easy to execute code at the same time the value of a property is set. You can use property procedures to do the following processing:

  • Before a property value is set to determine the value of the property.

  • After a property value is set, based on the new value.


Looping Through Code

 Copy code hover
[image]

Looping Through Code
Send feedback

Using conditional statements and looping statements (also called control structures), you can write Visual Basic code that makes decisions and repeats actions. Another useful control structure, the With statement, lets you to run a series of statements without having to requalify an object.

Using Conditional Statements to Make Decisions

Conditional statements evaluate whether a condition is True or False, and then specify one or more statements to run, depending on the result. Usually, a condition is an expression that uses a comparison operator to compare one value or variable with another.

Choosing a Conditional Statement to Use

  • If...Then...Else: Branching when a condition is True or False

  • Select Case: Selecting a branch from a set of conditions

Using Loops to Repeat Code

Looping allows you to run a group of statements repeatedly. Some loops repeat statements until a condition is False; others repeat statements until a condition is True. There are also loops that repeat statements a specific number of times or for each object in a collection.

Choosing a Loop to Use

  • Do...Loop: Looping while or until a condition is True

  • For...Next: Using a counter to run statements a specified number of times

  • For Each...Next: Repeating a group of statements for each object in a collection

Running Several Statements on the Same Object

In Visual Basic, usually you must specify an object before you can run one of its methods or change one of its properties. You can use the With statement to specify an object once for an entire series of statements.

  • With: Running a series of statements on the same object


Making Faster For...Next Loops

 Copy code hover
[image]

Making Faster For...Next Loops
Send feedback

Integers use less memory than the Variant data type and are slightly faster to update. However, this difference is only noticeable if you perform many thousands of operations. For example:

Copy code Copy code
Dim CountFaster As Integer    ' First case, use Integer.
For CountFaster = 0 to 32766
Next CountFaster

Dim CountSlower As Variant    ' Second case, use Variant.
For CountSlower = 0 to 32766
Next CountSlower

The first case above takes slightly less time to run than the second case. However, if CountFaster exceeds 32,767, an error occurs. To fix this, you can change CountFaster to the Long data type, which accepts a wider range of integers. In general, the smaller the data type, the less time it takes to update. Variants are slightly slower than their equivalent data type.


Passing Arguments Efficiently

 Copy code hover
[image]

Passing Arguments Efficiently
Send feedback

All arguments are passed to procedures by reference, unless you specify otherwise. This is efficient because all arguments passed by reference take the same amount of time to pass and the same amount of space (4 bytes) within a procedure regardless of the argument's data type.

You can pass an argument by value if you include the ByVal keyword in the procedure's declaration. Arguments passed by value consume from 2 - 16 bytes within the procedure, depending on the argument's data type. Larger data types take slightly longer to pass by value than smaller ones. Because of this, String and Variant data types generally should not be passed by value.

Passing an argument by value copies the original variable. Changes to the argument within the procedure aren't reflected back to the original variable. For example:

Copy code Copy code
Function Factorial (ByVal MyVar As Integer) ' Function declaration.
 MyVar = MyVar - 1
 If MyVar = 0 Then
 Factorial = 1
 Exit Function
 End If
 Factorial = Factorial(MyVar) * (MyVar + 1)
End Function

' Call Factorial with a variable S.
S = 5
Print Factorial(S) ' Displays 120 (the factorial of 5)
Print S ' Displays 5.

Without including ByVal in the function declaration, the preceding Print statements would display 1 and 0. This is because MyVar would then refer to variable would then refer to variable S , which is reduced by 1 until it equals 0.

Because ByVal makes a copy of the argument, it allows you to pass a variant to the Factorial function above. You can't pass a variant by reference if the procedure that declares the argument is another data type.


Returning Strings from Functions

 Copy code hover
[image]

Returning Strings from Functions
Send feedback

Some functions have two versions: one that returns a Variant data type and one that returns a String data type. The Variant versions are more convenient because variants handle conversions between different types of data automatically. They also allow Null to be propagated through an expression. The String versions are more efficient because they use less memory.

Consider using the String version when:

  • Your program is very large and uses many variables.

  • You write data directly to random-access files.

The following functions return values in a String variable when you append a dollar sign ($) to the function name. These functions have the same usage and syntax as their Variant equivalents without the dollar sign.

Chr$ | ChrB$ | *Command$
CurDir$ | Date$ | Dir$
Error$ | Format$ | Hex$
Input$ | InputB$ | LCase$
Left$ | LeftB$ | LTrim$
Mid$ | MidB$ | Oct$
Right$ | RightB$ | RTrim$
Space$ | Str$ | String$
Time$ | Trim$ | UCase$

* May not be available in all applications.


Understanding Automation

 Copy code hover
[image]

Understanding Automation
Send feedback

Automation (formerly OLE Automation) is a feature of the Component Object Model (COM), an industry-standard technology that applications use to expose their objects to development tools, macro languages, and other applications that support Automation. For example, a spreadsheet application may expose a worksheet, chart, cell, or range of cells — each as a different type of object. A word processor might expose objects such as an application, a document, a paragraph, a sentence, a bookmark, or a selection.

When an application supports Automation, the objects the application exposes can be accessed by Visual Basic. Use Visual Basic to manipulate these objects by invoking methods on the object or by getting and setting the object's properties. For example, you can create an Automation object named and write the following code to access the object:

Copy code Copy code
MyObj.Insert "Hello, world." ' Place text.
MyObj.Bold = True ' Format text.
If Mac = True ' Check your platform constant
 MyObj.SaveAs "HD:\WORDPROC\DOCS\TESTOBJ.DOC" ' Save the object (Macintosh).
Else
 MyObj.SaveAs "C:\WORDPROC\DOCS\TESTOBJ.DOC" ' Save the object (Windows).

Use the following functions to access an Automation object:

Function | Description
CreateObject | Creates a new object of a specified type.
GetObject | Retrieves an object from a file.

For details on the properties and methods supported by an application, see the application documentation. The objects, functions, properties, and methods supported by an application are usually defined in the application's object library.


Understanding Conditional Compilation

 Copy code hover
[image]

Understanding Conditional Compilation
Send feedback

You can use conditional compilation to run blocks of code selectively, for example, debugging statements comparing the speed of different approaches to the same programming task, or localizing an application for different languages.

You declare a conditional compiler constant in code with the #Const directive, and you denote blocks of code to be conditionally compiled with the #If...Then...#Else directive. The following example runs debug code or production code, based on the value of the variable.

Copy code Copy code
' Declare public compilation constant in Declarations section.
#Const conDebug = 1

Sub SelectiveExecution()
 #If conDebug = 1 Then
 . ' Run code with debugging statements.
 .
 .
 #Else
 . ' Run normal code.
 .
 .
 #End If
End Sub


Understanding Named Arguments and Optional Arguments

 Copy code hover
[image]

Understanding Named Arguments and Optional Arguments
Send feedback

When you call a Sub or Function procedure, you can supply arguments positionally, in the order they appear in the procedure's definition, or you can supply the arguments by name without regard to position.

For example, the following Sub procedure takes three arguments:

Copy code Copy code
Sub PassArgs(strName As String, intAge As Integer, dteBirth As Date)
 Debug.Print strName, intAge, dteBirth
End Sub

You can call this procedure by supplying its arguments in the correct position, each delimited by a comma, as shown in the following example:

Copy code Copy code
PassArgs "Mary", 29, #2-21-69#

You can also call this procedure by supplying named arguments, delimiting each with a comma.

Copy code Copy code
PassArgs intAge:=29, dteBirth:=#2/21/69#, strName:="Mary"

A named argument consists of an argument name followed by a colon and an equal sign (:=), followed by the argument value.

Named arguments are especially useful when you are calling a procedure that has optional arguments. If you use named arguments, you don't have to include commas to denote missing positional arguments. Using named arguments makes it easier to keep track of which arguments you passed and which you omitted.

Optional arguments are preceded by the Optional keyword in the procedure definition. You can also specify a default value for the optional argument in the procedure definition. For example:

Copy code Copy code
Sub OptionalArgs(strState As String, Optional strCountry As String = "USA")
. . .
End Sub

When you call a procedure with an optional argument, you can choose whether or not to specify the optional argument. If you don't specify the optional argument, the default value, if any, is used. If no default value is specified, the argument is it would be for any variable of the specified type.

The following procedure includes two optional arguments, the varRegion and and varCountry variables. The IsMissing function determines whether an optional Variant argument has been passed to the procedure.

Copy code Copy code
Sub OptionalArgs(strState As String, Optional varRegion As Variant, _
Optional varCountry As Variant = "USA")
 If IsMissing(varRegion) And IsMissing(varCountry) Then
 Debug.Print strState
 ElseIf IsMissing(varCountry) Then
 Debug.Print strState, varRegion
 ElseIf IsMissing(varRegion) Then
 Debug.Print strState, varCountry
 Else
 Debug.Print strState, varRegion, varCountry
 End If
End Sub

You can call this procedure using named arguments as shown in the following examples.

Copy code Copy code
OptionalArgs varCountry:="USA", strState:="MD"

OptionalArgs strState:= "MD", varRegion:=5


Understanding Objects, Properties, Methods, and Events

 Copy code hover
[image]

Understanding Objects, Properties, Methods, and Events
Send feedback

An object represents an element of an application, such as a worksheet, a cell, a chart, a form, or a report. In Visual Basic code, you must identify an object before you can apply one of the object's methods or change the value of one of its properties.

A collection is an object that contains several other objects, usually, but not always, of the same type. In Microsoft Excel, for example, the Workbooks object contains all the open Workbook objects. In Visual Basic, the Forms collection contains all the Form objects in an application.

Items in a collection can be identified by number or by name. For example, in the following procedure, identifies the first open Workbook object.

Copy code Copy code
Sub CloseFirst()
 Workbooks(1).Close
End Sub

The following procedure uses a name specified as a string to identify a Form object.

Copy code Copy code
Sub CloseForm()
 Forms("MyForm.frm").Close
End Sub

You can also manipulate an entire collection of objects if the objects share common methods. For example, the following procedure closes all open forms.

Copy code Copy code
Sub CloseAll()
 Forms.Close
End Sub

A method is an action that an object can perform. For example, Add is a method of the ComboBox object, because it adds a new entry to a combo box.

The following procedure uses the Add method to add a new item to a ComboBox.

Copy code Copy code
Sub AddEntry(newEntry as String)
 Combo1.Add newEntry
End Sub

A property is an attribute of an object that defines one of the object's characteristics, such as size, color, or screen location, or an aspect of its behavior, such as whether it is enabled or visible. To change the characteristics of an object, you change the values of its properties.

To set the value of a property, follow the reference to an object with a period, the property name, an equal sign (=), and the new property value. For example, the following procedure changes the caption of a Visual Basic form by setting the Caption property.

Copy code Copy code
Sub ChangeName(newTitle)
 myForm.Caption = newTitle
End Sub

You can't set some properties. The Help topic for each property indicates whether you can set that property (read-write), only read the property (read-only), or only write the property (write-only).

You can retrieve information about an object by returning the value of one of its properties. The following procedure uses a message box to display the title that appears at the top of the currently active form.

Copy code Copy code
Sub GetFormName()
 formName = Screen.ActiveForm.Caption
 MsgBox formName
End Sub

An event is an action recognized by an object, such as clicking the mouse or pressing a key, and for which you can write code to respond. Events can occur as a result of a user action or program code, or they can be triggered by the system.

Returning Objects

Every application has a way to return the objects it contains. However, they are not all the same, so you must refer to the Help topic for the object or collection you're using in the application to see how to return the object.


Understanding Parameter Arrays

 Copy code hover
[image]

Understanding Parameter Arrays
Send feedback

A parameter array can be used to pass an array of arguments to a procedure. You don't have to know the number of elements in the array when you define the procedure.

You use the ParamArray keyword to denote a parameter array. The array must be declared as an array of type Variant, and it must be the last argument in the procedure definition.

The following example shows how you might define a procedure with a parameter array.

Copy code Copy code
Sub AnyNumberArgs(strName As String, ParamArray intScores() As Variant)
 Dim intI As Integer

 Debug.Print strName; " Scores"
 ' Use UBound function to determine upper limit of array.
 For intI = 0 To UBound(intScores())
 Debug.Print " "; intScores(intI)
 Next intI
End Sub

The following examples show how you can call this procedure.

Copy code Copy code
AnyNumberArgs "Jamie", 10, 26, 32, 15, 22, 24, 16

AnyNumberArgs "Kelly", "High", "Low", "Average", "High"


Understanding Scope and Visibility

 Copy code hover
[image]

Understanding Scope and Visibility
Send feedback

Scope refers to the availability of a variable, constant, or procedure for use by another procedure. There are three scoping levels: procedure-level, private module-level, and public module-level.

You determine the scope of a variable when you declare it. It's a good idea to declare all variables explicitly to avoid naming-conflict errors between variables with different scopes.

Defining Procedure-Level Scope

A variable or constant defined within a procedure is not visible outside that procedure. Only the procedure that contains the variable declaration can use it. In the following example, the first procedure displays a message box that contains a string. The second procedure displays a blank message box because the variable is local to the first procedure.

Copy code Copy code
Sub LocalVariable()
 Dim strMsg As String
 strMsg = "This variable can't be used outside this procedure."
 MsgBox strMsg
End Sub

Sub OutsideScope()
 MsgBox strMsg
End Sub

Defining Private Module-Level Scope

You can define module-level variables and constants in the Declarations section of a module. Module-level variables can be either public or private. Public variables are available to all procedures in all modules in a project; private variables are available only to procedures in that module. By default, variables declared with the Dim statement in the Declarations section are scoped as private. However, by preceding the variable with the Private keyword, the scope is obvious in your code.

In the following example, the string variable strMsg is available to any procedures defined in the module. When the second procedure is called, it displays the contents of the string variable is available to any procedures defined in the module. When the second procedure is called, it displays the contents of the string variable strMsg in a dialog box.

Copy code Copy code
' Add following to Declarations section of module.
Private strMsg sAs String

Sub InitializePrivateVariable()
 strMsg = "This variable can't be used outside this module."
End Sub

Sub UsePrivateVariable()
 MsgBox strMsg
End Sub
Note Note

Public procedures in a standard module or class module are available to any referencing project. To limit the scope of all procedures in a module to the current project, add an Option Private Module statement to the Declarations section of the module. Public variables and procedures will still be available to other procedures in the current project, but not to referencing projects.

Defining Public Module-Level Scope

If you declare a module-level variable as public, it's available to all procedures in the project. In the following example, the string variable can be used by any procedure in any module in the project.

Copy code Copy code
' Include in Declarations section of module.
Public strMsg As String

All procedures are public by default, except for event procedures. When Visual Basic creates an event procedure, the Private keyword is automatically inserted before the procedure declaration. For all other procedures, you must explicitly declare the procedure with the Private keyword if you do not want it to be public.

You can use public procedures, variables, and constants defined in standard modules or class modules from referencing projects. However, you must first set a reference to the project in which they are defined.

Public procedures, variables, and constants defined in other than standard or class modules, such as form modules or report modules, are not available to referencing projects, because these modules are private to the project in which they reside.


Understanding the Lifetime of Variables

 Copy code hover
[image]

Understanding the Lifetime of Variables
Send feedback

The time during which a variable retains its value is known as its lifetime. The value of a variable may change over its lifetime, but it retains some value. When a variable loses scope, it no longer has a value.

When a procedure begins running, all variables are initialized. A numeric variable is initialized to zero, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with the character represented by the ASCII character code 0, or Chr(0). Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

When you declare an object variable, space is reserved in memory, but its value is set to Nothing until you assign an object reference to it using the Set statement.

If the value of a variable isn't changed during the running of your code, it retains its initialized value until it loses scope.

A procedure-level variable declared with the Dim statement retains a value until the procedure is finished running. If the procedure calls other procedures, the variable retains its value while those procedures are running as well.

If a procedure-level variable is declared with the Static keyword, the variable retains its value as long as code is running in any module. When all code has finished running, the variable loses its scope and its value. Its lifetime is the same as a module-level variable.

A module-level variable differs from a static variable. In a standard module or a class module, it retains its value until you stop running your code. In a class module, it retains its value as long as an instance of the class exists. Module-level variables consume memory resources until you reset their values, so use them only when necessary.

If you include the Static keyword before a Sub or Function statement, the values of all the procedure-level variables in the procedure are preserved between calls.


Understanding Variants

 Copy code hover
[image]

Understanding Variants
Send feedback

The Variant data type is automatically specified if you don't specify a data type when you declare a constant, variable, or argument. Variables declared as the Variant data type can contain string, date, time, Boolean, or numeric values, and can convert the values they contain automatically. Numeric Variant values require 16 bytes of memory (which is significant only in large procedures or complex modules) and they are slower to access than explicitly typed variables of any other type. You rarely use the Variant data type for a constant. String Variant values require 22 bytes of memory.

The following statements create Variant variables:

Copy code Copy code
Dim myVar
Dim yourVar As Variant
theVar = "This is some text."

The last statement does not explicitly declare the variable , but rather declares the variable implicitly, or automatically. Variables that are declared implicitly are specified as the Variant data type.

Tip Tip

If you specify a data type for a variable or argument, and then use the wrong data type, a data type error will occur. To avoid data type errors, either use only implicit variables (the Variant data type) or explicitly declare all your variables and specify a data type. The latter method is preferred.


Understanding Visual Basic Syntax

 Copy code hover
[image]

Understanding Visual Basic Syntax
Send feedback

The syntax in a Visual Basic Help topic for a method, statement, or function shows all the elements necessary to use the method, statement, or function correctly. The examples in this topic explain how to interpret the most common syntax elements.

Activate Method Syntax

object.Activate

In the Activate method syntax, the italic word "object" is a placeholder for information you supply — in this case, code that returns an object. Words that are bold should be typed exactly as they appear. For example, the following procedure activates the second window in the active document.

Copy code Copy code
Sub MakeActive()
    Windows(2).Activate
End Sub

MsgBox Function Syntax

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

In the MsgBox function syntax, the bold italic words are named arguments of the function. Arguments enclosed in brackets are optional. (Do not type the brackets in your Visual Basic code.) For the MsgBox function, the only argument you must provide is the text for the prompt.

Arguments for functions and methods can be specified in code either by position or by name. To specify arguments by position, follow the order presented in the syntax, separating each argument with a comma, for example:

Copy code Copy code
MsgBox "Your answer is correct!",0,"Answer Box"

To specify an argument by name, use the argument name followed by a colon and an equal sign (:=), and the argument's value. You can specify named arguments in any order, for example:

Copy code Copy code
MsgBox Title:="Answer Box", Prompt:="Your answer is correct!"

The syntax for functions and some methods shows the arguments enclosed in parentheses. These functions and methods return values, so you must enclose the arguments in parentheses to assign the value to a variable. If you ignore the return value or if you don't pass arguments at all, don't include the parentheses. Methods that don't return values do not need their arguments enclosed in parentheses. These guidelines apply whether you're using positional arguments or named arguments.

In the following example, the return value from the MsgBox function is a number indicating the selected button that is stored in the variable myVar. Because the return value is used, parentheses are required. Another message box then displays the value of the variable.

Copy code Copy code
Sub Question()
    myVar = MsgBox(Prompt:="I enjoy my job.", _
        Title:="Answer Box", Buttons:="4")
    MsgBox myVar
End Sub

Option Statement Syntax

Option Compare {Binary | Text | Database}

In the Option Compare statement syntax, the braces and vertical bar indicate a mandatory choice between three items. (Do not type the braces in the Visual Basic statement). For example, the following statement specifies that within the module, strings will be compared in a sort order that is not case-sensitive.

Copy code Copy code
Option Compare Text

Dim Statement Syntax

Dim varname[([subscripts])] [As type] [, varname[([subscripts])] [As type]] . . .

In the Dim statement syntax, the word Dim is a required keyword. The only required element is varname (the variable name). For example, the following statement creates three variables: myVar , nextVar , and thirdVar . These are automatically declared as Variant variables.

Copy code Copy code
Dim myVar, nextVar, thirdVar

The following example declares a variable as a String. Including a data type saves memory and can help you find errors in your code.

Copy code Copy code
Dim myAnswer As String

To declare several variables in one statement, include the data type for each variable. Variables declared without a data type are automatically declared as Variant.

Copy code Copy code
Dim x As Integer, y As Integer, z As Integer

In the following statement, x and y are assigned the Variant data type. Only z is assigned the Integer data type.

Copy code Copy code
Dim x, y, z As Integer

If you are declaring an array variable, you must include parentheses. The subscripts are optional. The following statement dimensions a dynamic array, myArray.

Copy code Copy code
Dim myArray()


Using Arrays

 Copy code hover
[image]

Using Arrays
Send feedback

You can declare an array to work with a set of values of the same data type. An array is a single variable with many compartments to store values, while a typical variable has only one storage compartment in which it can store only one value. Refer to the array as a whole when you want to refer to all the values it holds, or you can refer to its individual elements.

For example, to store daily expenses for each day of the year, you can declare one array variable with 365 elements, rather than declaring 365 variables. Each element in an array contains one value. The following statement declares the array variable with 365 elements. By default, an array is indexed beginning with zero, so the upper bound of the array is 364 rather than 365.

Copy code Copy code
Dim curExpense(364) As Currency

To set the value of an individual element, you specify the element's index. The following example assigns an initial value of 20 to each element in the array.

Copy code Copy code
Sub FillArray()
 Dim curExpense(364) As Currency
 Dim intI As Integer
 For intI = 0 to 364
 curExpense(intI) = 20
 Next
End Sub

Changing the Lower Bound

You can use the Option Base statement at the top of a module to change the default index of the first element from 0 to 1. In the following example, the Option Base statement changes the index for the first element, and the Dim statement declares the array variable with 365 elements.

Copy code Copy code
Option Base 1
Dim curExpense(365) As Currency

You can also explicitly set the lower bound of an array by using a To clause, as shown in the following example.

Copy code Copy code
Dim curExpense(1 To 365) As Currency
Dim strWeekday(7 To 13) As String

Storing Variant Values in Arrays

There are two ways to create arrays of Variant values. One way is to declare an array of Variant data type, as shown in the following example:

Copy code Copy code
Dim varData(3) As Variant
varData(0) = "Claudia Bendel"
varData(1) = "4242 Maple Blvd"
varData(2) = 38
varData(3) = Format("06-09-1952", "General Date")

The other way is to assign the array returned by the Array function to a Variant variable, as shown in the following example.

Copy code Copy code
Dim varData As Variant
varData = Array("Ron Bendel", "4242 Maple Blvd", 38, _
Format("06-09-1952", "General Date"))

You identify the elements in an array of Variant values by index, no matter which technique you use to create the array. For example, the following statement can be added to either of the preceding examples.

Copy code Copy code
MsgBox "Data for " & varData(0) & " has been recorded."

Using Multidimensional Arrays

In Visual Basic, you can declare arrays with up to 60 dimensions. For example, the following statement declares a 2-dimensional, 5-by-10 array.

Copy code Copy code
Dim sngMulti(1 To 5, 1 To 10) As Single

If you think of the array as a matrix, the first argument represents the rows and the second argument represents the columns.

Use nested For...Next statements to process multidimensional arrays. The following procedure fills a two-dimensional array with Single values.

Copy code Copy code
Sub FillArrayMulti()
 Dim intI As Integer, intJ As Integer
 Dim sngMulti(1 To 5, 1 To 10) As Single

 ' Fill array with values.
 For intI = 1 To 5
 For intJ = 1 To 10
 sngMulti(intI, intJ) = intI * intJ
 Debug.Print sngMulti(intI, intJ)
 Next intJ
 Next intI
End Sub


Using Constants

 Copy code hover
[image]

Using Constants
Send feedback

Your code might contain frequently occurring constant values, or might depend on certain numbers that are difficult to remember and have no obvious meaning. You can make your code easier to read and maintain using constants. A constant is a meaningful name that takes the place of a number or string that does not change. You can't modify a constant or assign a new value to it as you can a variable.

There are three types of constants:

Intrinsic constants or system-defined constants are provided by applications and controls. Other applications that provide object libraries, such as Microsoft Access, Microsoft Excel, Microsoft Project, and Microsoft Word also provide a list of constants you can use with their objects, methods, and properties. You can get a list of the constants provided for individual object libraries in the Object Browser.

Visual Basic constants are listed in the Visual Basic for Applications type library, and Data Access Object (DAO) library.

Note Note

Visual Basic continues to recognize constants in applications created in earlier versions of Visual Basic or Visual Basic for Applications. You can upgrade your constants to those listed in the Object Browser. Constants listed in the Object Browser don't have to be declared in your application.

  • Symbolic or user-defined constants are declared using the Const statement.

  • Conditional compiler constants are declared using the #Const statement.

In earlier versions of Visual Basic, constant names were usually capitalized with underscores. For example:

Copy code Copy code
TILE_HORIZONTAL

Intrinsic constants are now qualified to avoid the confusion when constants with the same name exist in more than one object library, which may have different values assigned to them. There are two ways to qualify constant names:

  • By prefix

  • By library reference

Qualifying Constants by Prefix

The intrinsic constants supplied by all objects appear in a mixed-case format, with a 2-character prefix indicating the object library that defines the constant. Constants from the Visual Basic for Applications object library are prefaced with "vb" and constants from the Microsoft Excel object library are prefaced with "xl". The following examples illustrate how prefixes for custom controls vary, depending on the type library.

  • vbTileHorizontal

  • xlDialogBorder

Qualifying Constants by Library Reference

You can also qualify the reference to a constant by using the following syntax:

[libname.] [modulename.]constname

The syntax for qualifying constants has these parts:

Part | Description
libname | Optional. The name of the type library that defines the constant. For most custom controls (not available on the Macintosh), this is also the class name of the control. If you don't remember the class name of the control, position the mouse pointer over the control in the toolbox. The class name is displayed in the ToolTip.
modulename | Optional. The name of the module within the type library that defines the constant. You can find the name of the module by using the Object Browser.
constname | The name defined for the constant in the type library.

For example:

Copy code Copy code
Threed.LeftJustify


Using Data Types Efficiently

 Copy code hover
[image]

Using Data Types Efficiently
Send feedback

Unless otherwise specified, undeclared variables are assigned the Variant data type. This data type makes it easy to write programs, but it is not always the most efficient data type to use.

You should consider using other data types if:

  • Your program is very large and uses many variables.

  • Your program must run as quickly as possible.

  • You write data directly to random-access files.

In addition to Variant, supported data types include Byte, Boolean, Integer, Long, Single, Double, Currency, Decimal, Date, Object, and String. Use the Dim statement to declare a variable of a specific type, for example:

Copy code Copy code
Dim X As Integer

This statement declares that a variable X is an integer — a whole number between -32,768 and 32,767. If you try to set X to a number outside that range, an error occurs. If you try to set X to a fraction, the number is rounded. For example:

Copy code Copy code
X = 32768        ' Causes error.
X = 5.9        ' Sets x to 6.


Using Do...Loop Statements

 Copy code hover
[image]

Using Do...Loop Statements
Send feedback

You can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True.

Repeating Statements While a Condition is True

There are two ways to use the While keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop , or you can check it after the loop has run at least once.

In the following ChkFirstWhile procedure, you check the condition before you enter the loop. If myNum is set to 9 instead of 20, the statements inside the loop will never run. In the ChkLastWhile procedure, the statements inside the loop run only once before the condition becomes False.

Copy code Copy code
Sub ChkFirstWhile()
    counter = 0
    myNum = 20
    Do While myNum > 10
        myNum = myNum - 1
        counter = counter + 1
    Loop
    MsgBox "The loop made " & counter & " repetitions."
End Sub

Sub ChkLastWhile()
    counter = 0
    myNum = 9
    Do
        myNum = myNum - 1
        counter = counter + 1
    Loop While myNum > 10
    MsgBox "The loop made " & counter & " repetitions."
End Sub

Repeating Statements Until a Condition Becomes True

There are two ways to use the Until keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the ChkFirstUntil procedure), or you can check it after the loop has run at least once (as shown in the ChkLastUntil procedure). Looping continues while the condition remains False.

Copy code Copy code
Sub ChkFirstUntil()
    counter = 0
    myNum = 20
    Do Until myNum = 10
        myNum = myNum - 1
        counter = counter + 1
    Loop
    MsgBox "The loop made " & counter & " repetitions."
End Sub

Sub ChkLastUntil()
    counter = 0
    myNum = 1
    Do
        myNum = myNum + 1
        counter = counter + 1
    Loop Until myNum = 10
    MsgBox "The loop made " & counter & " repetitions."
End Sub

Exiting a Do...Loop Statement from Inside the Loop

You can exit a Do...Loop using the Exit Do statement. For example, to exit an endless loop, use the Exit Do statement in the True statement block of either an If...Then...Else statement or a Select Case statement. If the condition is False, the loop will run as usual.

In the following example, myNum is assigned a value that creates an endless loop. The If...Then...Else statement checks for this condition, and then exits, preventing endless looping.

Copy code Copy code
Sub ExitExample()
    counter = 0
    myNum = 9
    Do Until myNum = 10
        myNum = myNum - 1
        counter = counter + 1
        If myNum < 10 Then Exit Do
    Loop
    MsgBox "The loop made " & counter & " repetitions."
End Sub
Note Note

To stop an endless loop, press ESC or CTRL+BREAK.


Using For Each...Next Statements

 Copy code hover
[image]

Using For Each...Next Statements
Send feedback

For Each...Next statements repeat a block of statements for each object in a collection or each element in an array. Visual Basic automatically sets a variable each time the loop runs. For example, the following procedure closes all forms except the form containing the procedure that's running.

Copy code Copy code
Sub CloseForms()
 For Each frm In Application.Forms
 If frm.Caption <> Screen. ActiveForm.Caption Then frm.Close
 Next
End Sub

The following code loops through each element in an array and sets the value of each to the value of the index variable I.

Copy code Copy code
Dim TestArray(10) As Integer, I As Variant
For Each I In TestArray
 TestArray(I) = I
Next I

Looping Through a Range of Cells

Use a For Each...Next loop to loop through the cells in a range. The following procedure loops through the range A1:D10 on Sheet1 and sets any number whose absolute value is less than 0.01 to 0 (zero).

Copy code Copy code
Sub RoundToZero()
 For Each myObject in myCollection
 If Abs(myObject.Value) < 0.01 Then myObject.Value = 0
 Next
End Sub

Exiting a For Each...Next Loop Before it is Finished

You can exit a For Each...Next loop using the Exit For statement. For example, when an error occurs, use the Exit For statement in the True statement block of either an If...Then...Else statement or a Select Case statement that specifically checks for the error. If the error does not occur, then the If…Then…Else statement is False and the loop continues to run as expected.

The following example tests for the first cell in the range A1:B5 that does not contain a number. If such a cell is found, a message is displayed and Exit For exits the loop.

Copy code Copy code
Sub TestForNumbers()
 For Each myObject In MyCollection
 If IsNumeric(myObject.Value) = False Then
 MsgBox "Object contains a non-numeric value."
 Exit For
 End If
 Next c
End Sub


Using For...Next Statements

 Copy code hover
[image]

Using For...Next Statements
Send feedback

You can use For...Next statements to repeat a block of statements a specific number of times. For loops use a counter variable whose value is increased or decreased with each repetition of the loop.

The following procedure makes the computer beep 50 times. The For statement specifies the counter variable and its start and end values. The Next statement increments the counter variable by 1.

VBA Copy code Copy code
Sub Beeps()
    For x = 1 To 50
        Beep
    Next x
End Sub

Using the Step keyword, you can increase or decrease the counter variable by the value you specify. In the following example, the counter variable j is incremented by 2 each time the loop repeats. When the loop is finished, total is the sum of 2, 4, 6, 8, and 10.

VBA Copy code Copy code
Sub TwosTotal()
    For j = 2 To 10 Step 2
        total = total + j
    Next j
    MsgBox "The total is " & total
End Sub

To decrease the counter variable, use a negative Step value. To decrease the counter variable, you must specify an end value that is less than the start value. In the following example, the counter variable myNum is decreased by 2 each time the loop repeats. When the loop is finished, total is the sum of 16, 14, 12, 10, 8, 6, 4, and 2.

VBA Copy code Copy code
Sub NewTotal()
    For myNum = 16 To 2 Step -2
        total = total + myNum
    Next myNum
    MsgBox "The total is " & total
End Sub
Note Note

It's not necessary to include the counter variable name after the Next statement. In the preceding examples, the counter variable name was included for readability.

You can exit a For...Next statement before the counter reaches its end value by using the Exit For statement. For example, when an error occurs, use the Exit For statement in the True statement block of either an If...Then...Else statement or a Select Case statement that specifically checks for the error. If the error doesn't occur, then the If…Then…Else statement is False, and the loop will continue to run as expected.


Using If...Then...Else Statements

 Copy code hover
[image]

Using If...Then...Else Statements
Send feedback

You can use the If...Then...Else statement to run a specific statement or a block of statements, depending on the value of a condition. If...Then...Else statements can be nested to as many levels as you need. However, for readability, you may want to use a Select Case statement rather than multiple levels of nested If...Then...Else statements.

Running Statements if a Condition is True

To run only one statement when a condition is True, use the single-line syntax of the If...Then...Else statement. The following example shows the single-line syntax, omitting the Else keyword:

Copy code Copy code
Sub FixDate()
 myDate = #2/13/95#
 If myDate < Now Then myDate = Now
End Sub

To run more than one line of code, you must use the multiple-line syntax. This syntax includes the End If statement, as shown in the following example:

Copy code Copy code
Sub AlertUser(value as Long)
 If value = 0 Then
 AlertLabel.ForeColor = "Red"
 AlertLabel.Font.Bold = True
 AlertLabel.Font.Italic = True
 End If
End Sub

Running Certain Statements if a Condition is True and Running Others if It's False

Use an If...Then...Else statement to define two blocks of executable statements: one block runs if the condition is True, the other block runs if the condition is False.

Copy code Copy code
Sub AlertUser(value as Long)
 If value = 0 Then
 AlertLabel.ForeColor = vbRed
 AlertLabel.Font.Bold = True
 AlertLabel.Font.Italic = True
 Else
 AlertLabel.Forecolor = vbBlack
 AlertLabel.Font.Bold = False
 AlertLabel.Font.Italic = False
 End If
End Sub

Testing a Second Condition if the First Condition is False

You can add ElseIf statements to an If...Then...Else statement to test a second condition if the first condition is False. For example, the following function procedure computes a bonus based on job classification. The statement following the Else statement runs if the conditions in all of the If and ElseIf statements are False.

Copy code Copy code
Function Bonus(performance, salary)
 If performance = 1 Then
 Bonus = salary * 0.1
 ElseIf performance = 2 Then
 Bonus = salary * 0.09
 ElseIf performance = 3 Then
 Bonus = salary * 0.07
 Else
 Bonus = 0
 End If
End Function


Using Parentheses in Code

 Copy code hover
[image]

Using Parentheses in Code
Send feedback

Sub procedures, built-in statements, and some methods don't return a value, so the arguments aren't enclosed in parentheses. For example:

Copy code Copy code
MySub "stringArgument", integerArgument

Function procedures, built-in functions, and some methods do return a value, but you can ignore it. If you ignore the return value, don't include parentheses. Call the function just as you would call a Sub procedure. Omit the parentheses, list any arguments, and don't assign the function to a variable. For example:

Copy code Copy code
MsgBox "Task Completed!", 0, "Task Box"

To use the return value of a function, enclose the arguments in parentheses, as shown in the following example.

Copy code Copy code
Answer3 = MsgBox("Are you happy with your salary?", 4, "Question 3")

A statement in a Sub or Function procedure can pass values to a called procedure using named arguments. The guidelines for using parentheses apply, whether or not you use named arguments. When you use named arguments, you can list them in any order, and you can omit optional arguments. Named arguments are always followed by a colon and an equal sign (:=), and then the argument value.

The following example calls the MsgBox function using named arguments, but it ignores the return value:

Copy code Copy code
MsgBox Title:="Task Box", Prompt:="Task Completed!"

The following example calls the MsgBox function using named arguments and assigns the return value to the variable :

Copy code Copy code
answer3 = MsgBox(Title:="Question 3", _
 Prompt:="Are you happy with your salary?", Buttons:=4)


Using Select Case Statements

 Copy code hover
[image]

Using Select Case Statements
Send feedback

Use the Select Case statement as an alternative to using ElseIf in If...Then...Else statements when comparing one expression to several different values. While If...Then...Else statements can evaluate a different expression for each ElseIf statement, the Select Case statement evaluates an expression only once, at the top of the control structure.

In the following example, the Select Case statement evaluates the argument that is passed to the procedure. Note that each Case statement can contain more than one value, a range of values, or a combination of values and comparison operators. The optional Case Else statement runs if the Select Case statement doesn't match a value in any of the Case statements.

Copy code Copy code
Function Bonus(performance, salary)
 Select Case performance
 Case 1
 Bonus = salary * 0.1
 Case 2, 3
 Bonus = salary * 0.09
 Case 4 To 6
 Bonus = salary * 0.07
 Case Is > 8
 Bonus = 100
 Case Else
 Bonus = 0
 End Select
End Function


Using the Add-In Manager

 Copy code hover
[image]

Using the Add-In Manager
Send feedback

Use the Add-In Manager dialog box to load or unload an add-in. If you close only the visible portions of an add-in — by double-clicking its system menu or by clicking its close button, for example — its forms disappear from the screen, but the add-in is still present in memory. The add-in object itself will always stay resident in memory until the add-in is disconnected through the Add-In Manager dialog box.


Using With Statements

 Copy code hover
[image]

Using With Statements
Send feedback

The With statement lets you specify an object or user-defined type once for an entire series of statements. With statements make your procedures run faster and help you avoid repetitive typing.

The following example fills a range of cells with the number 30, applies bold formatting, and sets the interior color of the cells to yellow.

Copy code Copy code
Sub FormatRange()
 With Worksheets("Sheet1").Range("A1:C10")
 .Value = 30
 .Font.Bold = True
 .Interior.Color = RGB(255, 255, 0)
 End With
End Sub

You can nest With statements for greater efficiency. The following example inserts a formula into cell A1, and then formats the font.

Copy code Copy code
Sub MyInput()
 With Workbooks("Book1").Worksheets("Sheet1").Cells(1, 1)
 .Formula = "=SQRT(50)"
 With .Font
 .Name = "Arial"
 .Bold = True
 .Size = 8
 End With
 End With
End Sub


Visual Basic Naming Rules

 Copy code hover
[image]

Visual Basic Naming Rules
Send feedback

Use the following rules when you name procedures, constants, variables, and arguments in a Visual Basic module:

  • You must use a letter as the first character.

  • You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name.

  • Name can't exceed 255 characters in length.

  • Generally, you shouldn't use any names that are the same as the functions, statements, and methods in Visual Basic. You end up shadowing the same keywords in the language. To use an intrinsic language function, statement, or method that conflicts with an assigned name, you must explicitly identify it. Precede the intrinsic function, statement, or method name with the name of the associated type library. For example, if you have a variable called Left , you can only invoke the Left function using VBA.Left .

  • You can't repeat names within the same level of scope. For example, you can't declare two variables named age within the same procedure. However, you can declare a private variable named age and a procedure-level variable named age within the same module.

    Note Note

    Visual Basic isn't case-sensitive, but it preserves the capitalization in the statement where the name is declared.


Working Across Applications

 Copy code hover
[image]

Working Across Applications
Send feedback

Visual Basic can create new objects and retrieve existing objects from many Microsoft applications. Other applications may also provide objects that you can create using Visual Basic. See the application's documentation for more information.

To create an new object or get an existing object from another application, use the CreateObject function or GetObject function:

Copy code Copy code
' Start Microsoft Excel and create a new Worksheet object.
Set ExcelWorksheet = CreateObject("Excel.Sheet")

' Start Microsoft Excel and open an existing Worksheet object.
Set ExcelWorksheet = GetObject("SHEET1.XLS")

' Start Microsoft Word.
Set WordBasic = CreateObject("Word.Basic")

Most applications provide an Exit or Quit method that closes the application whether or not it is visible. For more information on the objects, methods, and properties an application provides, see the application's documentation.

Some applications allow you to use the New keyword to create an object of any class that exists in its type library. For example:

Copy code Copy code
Dim X As New Field

In this case, is an example of a class in the data access type library. A new instance of a Field object is created using this syntax. Refer to the application's documentation for information about which object classes can be created in this way.


Writing a Function Procedure

 Copy code hover
[image]

Writing a Function Procedure
Send feedback

A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but a function can also return a value. A Function procedure can take arguments, such as constants, variables, or expressions that are passed to it by a calling procedure. If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A function returns a value by assigning a value to its name in one or more statements of the procedure.

In the following example, the Celsius function calculates degrees Celsius from degrees Fahrenheit. When the function is called from the Main procedure, a variable containing the argument value is passed to the function. The result of the calculation is returned to the calling procedure and displayed in a message box.

Copy code Copy code
Sub Main()
 temp = Application.InputBox(Prompt:= _
 "Please enter the temperature in degrees F.", Type:=1)
 MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub

Function Celsius(fDegrees)
 Celsius = (fDegrees - 32) * 5 / 9
End Function


Writing a Property Procedure

 Copy code hover
[image]

Writing a Property Procedure
Send feedback

A Property procedure is a series of Visual Basic statements that allow a programmer to create and manipulate custom properties.

  • Property procedures can be used to create read-only properties for forms, standard modules, and class modules.

  • Property procedures should be used instead of Public variables in code that must be executed when the property value is set.

  • Unlike Public variables, Property procedures can have Help strings assigned to them in the Object Browser.

When you create a Property procedure, it becomes a property of the module containing the procedure. Visual Basic provides the following three types of Property procedures:

Procedure | Description
Property Let | A procedure that sets the value of a property.
Property Get | A procedure that returns the value a property.
Property Set | A procedure that sets a reference to an object.

The syntax for declaring a Property procedure is:

[Public | Private] [Static] Property {Get | Let | Set} propertyname_ [(arguments)] [As type]

statements

End Property

Property procedures are usually used in pairs: Property Let with Property Get and Property Set with Property Get. Declaring a Property Get procedure alone is like declaring a read-only property. Using all three Property procedure types together is only useful for Variant variables, since only a Variant can contain either an object or other data type information. Property Set is intended for use with objects; Property Let isn't.

The required arguments in Property procedure declarations are shown in the following table:

Procedure | Declaration Syntax
Property Get | Property Get propname(1, …, n) As type
Property Let | Property Let propname(1, …,,,, n, n+1)
Property Set | Property Set propname(1, …, n, n+1)

The first argument through the next to last argument (1, …, n) must share the same names and data types in all Property procedures with the same name.

A Property Get procedure declaration takes one less argument than the related Property Let and Property Set declarations. The data type of the Property Get procedure must be the same as the data type as the data type of the last argument (n+1) in the related Property Let and Property Set declarations. For example, if you declare the following Property Let procedure, the Property Get declaration must use arguments with the same name and data type as the arguments in the Property Let procedure.

Copy code Copy code
Property Let Names(intX As Integer, intY As Integer, varZ As Variant)
 ' Statement here.
End Property

Property Get Names(intX As Integer, intY As Integer) As Variant
 ' Statement here.
End Property

The data type of the final argument in a Property Set declaration must be either an object type or a Variant.


Writing a Sub Procedure

 Copy code hover
[image]

Writing a Sub Procedure
Send feedback

A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements that performs actions but doesn't return a value. A Sub procedure can take arguments, such as constants, variables, or expressions that are passed by a calling procedure. If a Sub procedure has no arguments, the Sub statement must include an empty set of parentheses.

The following Sub procedure has comments explaining each line.

Copy code Copy code
' Declares a procedure named GetInfo
' This Sub procedure takes no arguments
Sub GetInfo()
' Declares a string variable named answer
Dim answer As String
' Assigns the return value of the InputBox function to answer
answer = InputBox(Prompt:="What is your name?")
 ' Conditional If...Then...Else statement
 If answer = Empty Then
 ' Calls the MsgBox function
 MsgBox Prompt:="You did not enter a name."
 Else
 ' MsgBox function concatenated with the variable answer
 MsgBox Prompt:="Your name is " & answer
 ' Ends the If...Then...Else statement
 End If
' Ends the Sub procedure
End Sub


Writing Assignment Statements

 Copy code hover
[image]

Writing Assignment Statements
Send feedback

Assignment statements assign a value or expression to a variable or constant. Assignment statements always include an equal sign (=). The following example assigns the return value of the InputBox function to the variable .

Copy code Copy code
Sub Question()
 Dim yourName As String
 yourName = InputBox("What is your name?")
 MsgBox "Your name is " & yourName
End Sub

The Let statement is optional and is usually omitted. For example, the preceding assignment statement can be written:

Copy code Copy code
Let yourName = InputBox("What is your name?").

The Set statement is used to assign an object to a variable that has been declared as an object. The Set keyword is required. In the following example, the Set statement assigns a range on Sheet1 to the object variable to the object variable myCell :

Copy code Copy code
Sub ApplyFormat()
Dim myCell As Range
Set myCell = Worksheets("Sheet1").Range("A1")
 With myCell.Font
 .Bold = True
 .Italic = True
 End With
End Sub

Statements that set property values are also assignment statements. The following example sets the Bold property of the Font object for the active cell:

Copy code Copy code
ActiveCell.Font.Bold = True


Writing Data to Files

 Copy code hover
[image]

Writing Data to Files
Send feedback

When working with large amounts of data, it is often convenient to write data to or read data from a file. The Open statement lets you create and access files directly. Open provides three types of file access:

  • Sequential access (Input, Output, and Append modes) is used for writing text files, such as error logs and reports.

  • Random access (Random mode) is used to read and write data to a file without closing it. Random access files keep data in records, which makes it easy to locate information quickly.

  • Binary access (Binary mode) is used to read or write to any byte position in a file, such as storing or displaying a bitmap image.

    Note Note

    The Open statement should not be used to open an application's own file types. For example, don't use Open to open a Word document, a Microsoft Excel spreadsheet, or a Microsoft Access database. Doing so will cause loss of file integrity and file corruption.

The following table shows the statements typically used when writing data to and reading data from files.

Access Type | Writing Data | Reading Data
Sequential | Print #, Write # | Input #
Random | Put | Get
Binary | Put | Get


Writing Declaration Statements

 Copy code hover
[image]

Writing Declaration Statements
See also Send feedback

You use declaration statements to name and define procedures, variables, arrays, and constants. When you declare a procedure, variable, or constant, you also define its scope, depending on where you place the declaration and what keywords you use to declare it.

The following example contains three declarations.

Copy code Copy code
Sub ApplyFormat()
    Const limit As Integer = 33
    Dim myCell As Range
    ' More statements
End Sub

The Sub statement (with matching End Sub statement) declares a procedure named ApplyFormat. All the statements enclosed by the Sub and End Sub statements are executed whenever the ApplyFormat procedure is called or run.

The Const statement declares the constant limit specifying the Integer data type and a value of 33.

The Dim statement declares the myCell variable. The data type is an object, in this case, a Microsoft Excel Range object. You can declare a variable to be any object that is exposed in the application you are using. Dim statements are one type of statement used to declare variables. Other keywords used in declarations are ReDim, Static, Public, Private, and Const.

See also

Concepts

Writing a Sub Procedure
Declaring Constants
Declaring Variables


Writing Executable Statements

 Copy code hover
[image]

Writing Executable Statements
Send feedback

An executable statement initiates action. It can execute a method or function, and it can loop or branch through blocks of code. Executable statements often contain mathematical or conditional operators.

The following example uses a For Each...Next statement to iterate through each cell in a range named MyRange on Sheet1 of an active Microsoft Excel workbook. The variable c is a cell in the collection of cells contained in on Sheet1 of an active Microsoft Excel workbook. The variable c is a cell in the collection of cells contained in MyRange .

VBA Copy code Copy code
Sub ApplyFormat()
Const limit As Integer = 33
For Each c In Worksheets("Sheet1").Range("MyRange").Cells
    If c.Value > limit Then
        With c.Font
            .Bold = True
            .Italic = True
        End With
    End If
Next c
MsgBox "All done!"
End Sub

The If...Then...Else statement in the example checks the value of the cell. If the value is greater than 33, the With statement sets the Bold and Italic properties of the Font object for that cell. If...Then...Else statements end with End If.

The With statement can save typing because the statements it contains are automatically executed on the object following the With keyword.

The Next statement calls the next cell in the collection of cells contained in MyRange.

The MsgBox function (which displays a built-in Visual Basic dialog box) displays a message indicating that the Sub procedure has finished running.


Writing Visual Basic Statements

 Copy code hover
[image]

Writing Visual Basic Statements
Send feedback

A statement in Visual Basic is a complete instruction. It can contain keywords, operators, variables, constants, and expressions. Each statement belongs to one of the following three categories:

  • Declaration statements, which name a variable, constant, or procedure and can also specify a data type. Writing Declaration Statements

  • Assignment statements, which assign a value or expression to a variable or constant. Writing Assignment Statements

  • Executable statements, which initiate actions. These statements can execute a method or function, and they can loop or branch through blocks of code. Executable statements often contain mathematical or conditional operators. Writing Executable Statements

Continuing a Statement over Multiple Lines

A statement usually fits on one line, but you can continue a statement onto the next line using a line-continuation character. In the following example, the MsgBox executable statement is continued over three lines:

Copy code Copy code
Sub DemoBox() 'This procedure declares a string variable,
 ' assigns it the value Claudia, and then displays
 ' a concatenated message.
 Dim myVar As String
 myVar = "John"
 MsgBox Prompt:="Hello " & myVar, _
 Title:="Greeting Box", _
 Buttons:=vbExclamation
End Sub

Adding Comments

Comments can explain a procedure or a particular instruction to anyone reading your code. Visual Basic ignores comments when it runs your procedures. Comment lines begin with an apostrophe (') or with Rem followed by a space, and can be added anywhere in a procedure. To add a comment to the same line as a statement, insert an apostrophe after the statement, followed by the comment. By default, comments are displayed as green text.

Checking Syntax Errors

If you press ENTER after typing a line of code and the line is displayed in red (an error message may display as well), you must find out what's wrong with your statement, and then correct it.


Visual Basic definitions

 Copy code hover
[image]

Visual Basic definitions
Send feedback

In this section

  • VBE Glossary


VBE Glossary

 Copy code hover
[image]

VBE Glossary
Send feedback

access key

A key pressed while holding down the ALT key that allows the user to open a menu, carry out a command, select an object, or move to an object. For example, ALT+F opens the File menu.

ActiveX control

An object that you place on a form to enable or enhance a user's interaction with an application. ActiveX Controls have events and can be incorporated into other controls. These controls have an .ocx file name extension.

ActiveX object

An object that is exposed to other applications or programming tools through Automation interfaces.

add-in

A customized tool that adds capabilities to the Visual Basic development environment.

ANSI Character Set

American National Standards Institute (ANSI) 8-bit character set used to represent up to 256 characters (0-255) using your keyboard. The first 128 characters (0-127) correspond to the letters and symbols on a standard U.S. keyboard. The second 128 characters (128-255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.

application

A collection of code and visual elements that work together as a single program. Developers can build and run applications within the development environment, while users usually run applications as executable files outside the development environment.

argument

A constant, variable, or expression passed to a procedure.

array

A set of sequentially indexed elements having the same intrinsic data type. Each element of an array has a unique identifying index number. Changes made to one element of an array don't affect the other elements.

ASCII Character Set

American Standard Code for Information Interchange (ASCII) 7-bit character set used to represent letters and symbols found on a standard U.S. keyboard. The ASCII character set is the same as the first 128 characters (0-127) in the ANSI character set.

automatic formatting

A feature that automatically formats code as you enter it by capitalizing the first letter for keywords, standardizing spacing, adding punctuation, and setting the foreground and background colors.

base class

Original class from which other classes can be derived by inheritance.

bitmap

An image represented by pixels and stored as a collection of bits in which each bit corresponds to one pixel. On color systems, more than one bit corresponds to each pixel. A bitmap usually has a .bmp file name extension.

bitwise comparison

A bit-by-bit comparison between identically positioned bits in two numeric expressions.

Boolean expression

An expression that evaluates to either True or False.

Boolean data type

A data type with only two possible values, True (-1) or False (0). Boolean variables are stored as 16-bit (2-byte) numbers.

bound control

A data-aware control that can provide access to a specific field or fields in a database through a Data control. A data-aware control is typically bound to a Data control through its DataSource and DataField properties. When a Data control moves from one record to the next, all bound controls connected to the Data control change to display data from fields in the current record. When users change data in a bound control and then move to a different record, the changes are automatically saved in the database.

break mode

Temporary suspension of program execution in the development environment. In break mode, you can examine, debug, reset, step through, or continue program execution. You enter break mode when you:

  • Encounter a breakpoint during program execution.

  • Press CTRL+BREAK during program execution.

  • Encounter a Stop statement or untrapped run-time error during program execution.

  • Add a Break When True watch expression. Execution stops when the value of the watch changes and evaluates to True.

  • Add a Break When Changed watch expression. Execution stops when the value of the watch changes.

breakpoint

A selected program line at which execution automatically stops. Breakpoints are not saved with your code.

by reference

A way of passing the address of an argument to a procedure instead of passing the value. This allows the procedure to access the actual variable. As a result, the variable's actual value can be changed by the procedure to which it is passed. Unless otherwise specified, arguments are passed by reference.

Byte data type

A data type used to hold positive integer numbers ranging from 0-255. Byte variables are stored as single, unsigned 8-bit (1-byte) numbers.

by value

A way of passing the value of an argument to a procedure instead of passing the address. This allows the procedure to access a copy of the variable. As a result, the variable's actual value can't be changed by the procedure to which it is passed.

character code

A number that represents a particular character in a set, such as the ANSI character set.

class

The formal definition of an object. The class acts as the template from which an instance of an object is created at run time. The class defines the properties of the object and the methods used to control the object's behavior.

class module

A module that contains the definition of a class, including its property and method definitions.

code module

A module containing public code that can be shared among all modules in a project. A code module is referred to as a standard module in later versions of Visual Basic.

code pane

A pane contained in a code window that is used for entering and editing code. A code window can contain one or more code panes.

collection

An object that contains a set of related objects. An object's position in the collection can change whenever a change occurs in the collection; therefore, the position of any specific object in the collection can vary.

command line

The path, file name, and argument information provided by the user to run a program.

comment

Text added to code that explains how the code works. In Visual Basic, a comment line can start with either an apostrophe (') or with the Rem keyword followed by a space.

comparison operator

A character or symbol indicating a relationship between two or more values or expressions. These operators include less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), not equal (<>), and equal (=). Additional comparison operators include Is and Like. Note that Is and Like can't be used as comparison operators in a Select Case statement.

compiler directive

A command used to alter the action of the compiler.

compile time

The period during which source code is translated to executable code.

conditional compiler constant

A Visual Basic identifier that is defined using the #Const compiler directive or defined in the host application and used by other compiler directives to determine when or if certain blocks of Visual Basic code are compiled.

constant

A named item that retains a constant value throughout the execution of a program. A constant can be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except Is and exponentiation. Each host application can define its own set of constants. Additional constants can be defined by the user with the Const statement. You can use constants anywhere in your code in place of actual values.

container

An object that can contain other objects.

control

An object you can place on a form that has its own set of recognized properties, methods, and events. You use controls to receive user input, display output, and trigger event procedures. You can manipulate most controls using methods. Some controls are interactive (responsive to user actions), while others are static (accessible only through code).

control array

A group of controls that share a common name, type, and event procedures. Each control in an array has a unique index number that can be used to determine which control recognizes an event.

Currency data type

A data type with a range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807. Use this data type for calculations involving money and for fixed-point calculations where accuracy is particularly important. The at sign (@) type-declaration character represents Currency in Visual Basic.

data type

The characteristic of a variable that determines what kind of data it can hold. Data types include Byte, Boolean, Integer, Long, Currency, Decimal, Single, Double, Date, String, Object, Variant (default), and user-defined types, as well as specific types of objects.

Date data type

A data type used to store dates and times as a real number. Date variables are stored as 64-bit (8-byte) numbers. The value to the left of the decimal represents a date, and the value to the right of the decimal represents a time.

date expression

Any expression that can be interpreted as a date, including date literals, numbers that look like dates, strings that look like dates, and dates returned from functions. A date expression is limited to numbers or strings, in any combination, that can represent a date from January 1, 100 - December 31, 9999.

Dates are stored as part of a real number. Values to the left of the decimal represent the date; values to the right of the decimal represent the time. Negative numbers represent dates prior to December 30, 1899.

date literal

Any sequence of characters with a valid format that is surrounded by number signs (#). Valid formats include the date format specified by the locale settings for your code or the universal date format.

For example, #12/31/92# is the date literal that represents December 31, 1992, where English-U.S. is the locale setting for your application. Use date literals to maximize portability across national languages.

date separators

Characters used to separate the day, month, and year when date values are formatted. The characters are determined by system settings or by the Format function.

DBCS

A character set that uses 1 or 2 bytes to represent a character, allowing more than 256 characters to be represented.

dynamic data exchange (DDE)

An established protocol for exchanging data through active links between applications that run under Microsoft Windows.

Decimal data type

A data type that contains decimal numbers scaled by a power of 10. For zero-scaled numbers, that is, numbers with no decimal places, the range is +/-79,228,162,514,264,337,593,543,950,335. For numbers with 28 decimal places the range is +/-7.9228162514264337593543950335. The smallest non-zero number that can be represented as a Decimal is 0.0000000000000000000000000001.

Note that at this time the Decimal data type can only be used within a Variant. You cannot declare a variable to be of type Decimal. You can, however, create a Variant whose subtype is Decimal using the CDec function.

declaration

Nonexecutable code that names a constant, variable, or procedure, and specifies its characteristics, such as data type. For DLL procedures, declarations specify names, libraries, and arguments.

designer

Provides a visual design window in the Visual Basic development environment. You can use this window to design new classes visually. Visual Basic has built-in designers for forms. The Professional and Enterprise editions of Visual Basic include designers for ActiveX controls and ActiveX documents.

design time

The time during which you build an application in the development environment by adding controls, setting control or form properties, and so on. In contrast, during run time, you interact with the application like a user.

development environment

The part of the application where you write code, create controls, set control and form properties, and so on. This contrasts with running the application.

dynamic-link library (DLL)

A library of routines loaded and linked into applications at run time. DLLs are created with other programming languages such as C, MASM, or FORTRAN.

docked window

A window that is attached to the frame of the main window.

document

Any self-contained work created with an application and given a unique file name.

Double data type

A data type that holds double-precision floating-point numbers as 64-bit numbers in the range -1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. The number sign (#) type-declaration character represents the Double in Visual Basic.

Empty

Indicates that no beginning value has been assigned to a Variant variable. An Empty variable is represented as 0 in a numeric context or a zero-length string ("") in a string context.

error number

A whole number in the range 0 - 65,535 that corresponds to the Number property setting of the Err object. When combined with the Description property setting of the Err object, this number represents a particular error message.

event source object

An object that is the source of events that occur in response to an action. An event source object is returned by a property. For example, the CommandBarEvents property returns the CommandBarEvents object.

executable file

A Windows-based application that can run outside the development environment. An executable file has an .exe file name extension.

expression

A combination of keywords, operators, variables, and constants that yields a string, number, or object. An expression can be used to perform a calculation, manipulate characters, or test data.

file number

Number used in the Open statement to open a file. Use file numbers in the range 1-255, inclusive, for files not accessible to other applications. Use file numbers in the range 256-511 for files accessible from other applications.

focus

The ability to receive mouse clicks or keyboard input at any one time. In the Microsoft Windows environment, only one window, form, or control can have this ability at a time. The object that "has the focus" is normally indicated by a highlighted caption or title bar. The focus can be set by the user or by the application.

form

A window or dialog box. Forms are containers for controls. A multiple-document interface (MDI) form can also act as a container for child forms and some controls.

form module

A file in a Visual Basic project with an .frm file name extension that can contain graphical descriptions of a form; its controls and their property settings; form-level declarations of constants, variables, and external procedures; and event and general procedures.

Function procedure

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. In contrast, an event procedure is invoked automatically in response to a user or system action.

graphics method

A method that operates on an object such as a Form, PictureBox, or Printer, and performs run-time drawing operations such as animation or simulation. The graphics methods are Circle, Cls, Line, PaintPicture, Point, Print, and PSet.

host application

Any application that supports the use of Visual Basic for Applications, for example, Microsoft Excel, Microsoft Project, and so on.

icon

A graphical representation of an object or concept; commonly used to represent minimized applications in Microsoft Windows. An icon is a bitmap with a maximum size of 32 x 32 pixels. Icons have an .ico file name extension.

identifier

An element of an expression that refers to a constant or variable.

in process

Running in the same address space as an application.

insertable object

An application object that is a type of custom control, such as a Microsoft Excel worksheet.

Integer data type

A data type that holds integer variables stored as 2-byte whole numbers in the range -32,768 to 32,767. The Integer data type is also used to represent enumerated values. The percent sign (%) type-declaration character represents an Integer in Visual Basic.

intrinsic constants

A constant provided by an application. Visual Basic constants are listed in the object library and can be viewed with the Object Browser. Because you can't disable intrinsic constants, you can't create a user-defined constant with the same name.

keyword

A word or symbol recognized as part of the Visual Basic programming language; for example, a statement, function name, or operator.

line-continuation character

The combination of a space followed by an underscore ( _) used in the development environment to extend a single logical line of code to two or more physical lines. However, you can't use a line-continuation character to continue a line of code within a string expression.

line label

Used to identify a single line of code. A line label can be any combination of characters that starts with a letter and ends with a colon (:). Line labels are not case sensitive and must begin in the first column.

line number

Used to identify a single line of code. A line number can be any combination of digits that is unique within the module where it is used. Line numbers must begin in the first column.

linked window

A window that is joined to another window other than the main window.

linked window frame

A window frame containing multiple windows that have been linked together.

locale

The set of information that corresponds to a given language and country/region. The code locale setting affects the language of terms such as keywords and defines locale-specific settings such as the decimal and list separators, date formats, and character sorting order.

The system locale setting affects the way locale-aware functionality behaves, for example, when you display numbers or convert strings to dates. You set the system locale using the Control Panel utilities provided by the operating system.

Although the code locale and system locale are generally set to the same setting, they may differ in some situations. For example, in Visual Basic, Standard Edition and Visual Basic, Professional Edition, the code is not translated from English-U.S. The system locale can be set to the user's language and country/region, but the code locale is always set to English-U.S. and can't be changed. In this case, the English-U.S. separators, format placeholders, and sorting order are used.

logic error

A programming error that can cause code to produce incorrect results or stop execution. For example, a logic error can be caused by incorrect variable names, incorrect variable types, endless loops, flaws in comparisons, or array problems.

Long data type

A 4-byte integer ranging in value from -2,147,483,648 to 2,147,483,647. The ampersand (&) type-declaration character represents a Long in Visual Basic.

margin indicator

An icon displayed in the Margin Indicator bar in the Code window. Margin indicators provide visual cues during code editing.

MDI child

A form contained within an MDI form in a multiple-document interface (MDI) application. To create a child form, set the MDIChild property of the MDI form to True.

MDI form

A window that makes up the background of a multiple-document interface (MDI) application. The MDI form is the container for any MDI child forms in the application.

member

An element of a collection, object, or user-defined type.

metafile

A file that stores an image as graphical objects such as lines, circles, and polygons rather than as pixels. There are two types of metafiles, standard and enhanced. Standard metafiles usually have a .wmf file name extension. Enhanced metafiles usually have a .emf file name extension. Metafiles preserve an image more accurately than pixels when the image is resized.

method

A procedure that acts on an object.

module

A set of declarations followed by procedures.

module level

Describes code in the Declarations section of a module. Any code outside a procedure is referred to as module-level code. Declarations must be listed first, followed by procedures.

module variable

A variable declared outside Function, Sub, or Property procedure code. Module variables must be declared outside any procedures in the module. They exist while the module is loaded and are visible in all procedures in the module.

named argument

An argument that has a name that is predefined in the object library. Instead of providing a value for each argument in a specified order expected by the syntax, you can use named arguments to assign values in any order. For example, suppose a method accepts three arguments:

DoSomeThing namedarg1, namedarg2, namedarg3

By assigning values to named arguments, you can use the following statement:

Copy code Copy code
DoSomeThing namedarg3 := 4, namedarg2 := 5, namedarg1 := 20

Note that the named arguments don't have to appear in the normal positional order in the syntax.

Null

A value indicating that a variable contains no valid data. Null is the result of an explicit assignment of Null to a variable or any operation between expressions that contain Null.

numeric data type

Any intrinsic numeric data type (Byte, Boolean, Integer, Long, Currency, Single, Double, or Date).

numeric expression

Any expression that can be evaluated as a number. Elements of an expression can include any combination of keywords, variables, constants, and operators that result in a number.

numeric type

Any intrinsic numeric data type (Byte, Boolean, Integer, Long, Currency, Single, Double, or Date) or any Variant numeric subtype (Empty, Integer, Long, Single, Double, Currency, Decimal, Date, Error, Boolean, or Byte).

object

A combination of code and data that can be treated as a unit, for example, a control, form, or application component. Each object is defined by a class.

Object box

A list box at the upper-left corner of the Code window that lists the form and controls in the form to which the code is attached, or a list box located at the top of the Properties window that lists the form and its controls.

Object Browser

A dialog box in which you can examine the contents of an object library to get information about the objects provided.

Object data type

A data type that represents any Object reference. Object variables are stored as 32-bit (4-byte) addresses that refer to objects.

object expression

An expression that specifies a particular object and can include any of the object's containers. For example, an application can have an Application object that contains a Document object that contains a Text object.

object library

A file with the .olb extension that provides information to Automation controllers (like Visual Basic) about available objects. You can use the Object Browser to examine the contents of an object library to get information about the objects provided.

object module

A module that contains code specific to an object, for example, class module, form module, and document module. Object modules contain the code behind their associated objects. The rules for object modules differ from those for standard modules.

object type

A type of object exposed by an application through Automation, for example, Application, File, Range, and Sheet. Use the Object Browser or refer to the application's documentation for a complete listing of available objects.

object variable

A variable that contains a reference to an object.

Automation object

An object that is exposed to other applications or programming tools through Automation interfaces.

parameter

Variable name by which an argument passed to a procedure is known within the procedure. This variable receives the argument passed into the procedure. Its scope ends when the procedure ends.

path

A string expression specifying a directory or folder location. The location can include a drive specification.

pi

A mathematical constant equal to approximately 3.1415926535897932.

point

A point is 1/72 inch. Font sizes are usually measured in points.

print zone

Print zones begin every 14 columns. The width of each column is an average of the width of all characters in the point size for the selected font.

Private

Variables that are visible only to the module in which they are declared.

procedure

A named sequence of statements executed as a unit. For example, Function, Property, and Sub are types of procedures. A procedure name is always defined at module level. All executable code must be contained in a procedure. Procedures can't be nested within other procedures.

Procedure box

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

procedure call

A statement in code that tells Visual Basic to execute a procedure.

procedure level

Describes statements located within a Function, Property, or Sub procedure. Declarations are usually listed first, followed by assignments and other executable code.

Note that module-level code resides outside a procedure block.

project

A set of modules.

Project window

A window that displays a list of the form, class, and standard modules; the resource file; and references in your project. Files with .ocx and .vbx file name extensions aren't displayed in the Project window.

Properties window

A window used to display or change properties of a selected form or control at design time. Some custom controls have customized Properties windows.

property

A named attribute of an object. Properties define object characteristics such as size, color, and screen location, or the state of an object, such as enabled or disabled.

Property procedure

A procedure that creates and manipulates properties for a class module. A Property procedure begins with a Property Let, Property Get, or Property Set statement and ends with an End Property statement.

Public

Variables declared using the Public statement are visible to all procedures in all modules in all applications unless Option Private Module is in effect. In that case, the variables are public only within the project in which they reside.

referenced project

The project you directly create a link to from the current project you are working on. A project referenced by one of the current project's directly referenced projects is called an indirectly referenced project. Its Public variables are not accessible to the current project except through qualification with its project name. Any combination of direct and indirect references between projects is valid as long as they do not result in a complete cycle.

referencing project

The current project. How you create a link to a project depends on the host application. For example, to directly reference a project in Microsoft Excel, select the project from the References dialog box of the Tools menu. Public variables in a directly referenced project are visible to the directly referencing project, but Public variables in a directly referencing project are not visible to a directly referenced project.

registry

In Microsoft Windows version 3.1, OLE registration information and file associations are stored in the registration database, and program settings are stored in Windows system initialization (.ini) files. In Microsoft Windows 95, the Windows registry serves as a central configuration database for user, application, and computer-specific information, including the information previously contained in both the Windows version 3.1 registration database and .ini files.

resource file

A file in a Visual Basic project with an .res file name extension that can contain bitmaps, text strings, or other data. By storing this data in a separate file, you can change the information without editing your code. Only one resource file can be associated with a project.

run-time error

An error that occurs when code is running. A run-time error results when a statement attempts an invalid operation.

run time

The time during which code is running. During run time, you can't edit the code.

scope

Defines the visibility of a variable, procedure, or object. For example, a variable declared as Public is visible to all procedures in all modules in a directly referencing project unless Option Private Module is in effect. When Option Private Module is in effect, the module itself is private and therefore not visible to referencing projects. Variables declared in a procedure are visible only within the procedure and lose their value between calls unless they are declared Static.

seed

An initial value used to generate pseudorandom numbers. For example, the Randomize statement creates a seed number used by the Rnd function to create unique pseudorandom number sequences.

Single data type

A data type that stores single-precision floating-point variables as 32-bit (4-byte) floating-point numbers, ranging in value from -3.402823E38 to -1.401298E-45 for negative values, and 1.401298E-45 to 3.402823E38 for positive values. The exclamation point (!) type-declaration character represents a Single in Visual Basic.

sort order

A sequencing principle used to order data, for example, alphabetic, numeric, ascending, descending, and so on.

stack

A fixed amount of memory used by Visual Basic to preserve local variables and arguments during procedure calls.

standard module

A module containing only procedure, type, and data declarations and definitions. Module-level declarations and definitions in a standard module are Public by default. A standard module is referred to as a code module in earlier versions of Visual Basic.

statement

A syntactically complete unit that expresses one kind of action, declaration, or definition. A statement generally occupies a single line, although you can use a colon (:) to include more than one statement on a line. You can also use a line-continuation character (_) to continue a single logical line onto a second physical line.

string comparison

A comparison of two sequences of characters. Use Option Compare to specify binary or text comparison. In English-U.S., binary comparisons are case sensitive; text comparisons are not.

string constant

Any constant (defined using the Const keyword) consisting of a sequence of contiguous characters interpreted as the characters themselves rather than as a numeric value.

String data type

A data type consisting of a sequence of contiguous characters that represent the characters themselves rather than their numeric values. A String can include letters, numbers, spaces, and punctuation. The String data type can store fixed-length strings ranging in length from 0 to approximately 63K characters and dynamic strings ranging in length from 0 to approximately 2 billion characters. The dollar sign ($) type-declaration character represents a String in Visual Basic.

string expression

Any expression that evaluates to a sequence of contiguous characters. Elements of a string expression can include a function that returns a string, a string literal, a string constant, a string variable, a string Variant, or a function that returns a string Variant (VarType 8).

string literal

Any expression consisting of a sequence of contiguous characters surrounded by quotation marks that is literally interpreted as the characters within the quotation marks.

Sub procedure

A procedure that performs a specific task within a program, but returns no explicit value. A Sub procedure begins with a Sub statement and ends with an End Sub statement.

syntax checking

A feature that checks your code for correct syntax. If the syntax checking feature is enabled, a message is displayed when you enter code that contains a syntax error and the suspect code is highlighted.

syntax error

An error that occurs when you enter a line of code that Visual Basic doesn't recognize.

Note that syntax rules for individual keywords are defined in the Syntax section of the associated Help topic. To get Help on a keyword from within the development environment, select the keyword and press F1.

tab order

The order in which the focus moves from one field to the next as you press TAB or SHIFT+TAB.

time expression

Any expression that can be interpreted as a time. This includes any combination of time literals, numbers that look like times, strings that look like times, and times returned from functions.

Times are stored as part of a real number. Values to the right of the decimal represent the time. For example, midday (12:00 P.M.) is represented by 0.5.

twip

A unit of screen measurement equal to 1/20 point. A twip is a screen-independent unit used to ensure that placement and proportion of screen elements in your screen application are the same on all display systems. There are approximately 1440 twips to a logical inch or 567 twips to a logical centimeter (the length of a screen item measuring one inch or one centimeter when printed).

type-declaration character

A character appended to a variable name indicating the variable's data type. By default, variables are of type Variant unless a corresponding Def type statement is present in the module.

type library

A file or component within another file that contains standard descriptions of exposed objects, properties, and methods that are available for Automation. Object library files (.olb) contain type libraries.

Unicode

International Standards Organization (ISO) character standard. Unicode uses a 16-bit (2-byte) coding scheme that allows for 65,536 distinct character spaces. Unicode includes representations for punctuation marks, mathematical symbols, and dingbats, with substantial room for future expansion.

universal date format

The universal date format is #yyyy-mm-dd hh:mm:ss#. However, both the date component (#yyyy-mm-dd#) and the time component (#hh:mm:ss#) can be represented separately.

user-defined type

Any data type defined using the Type statement. User-defined data types can contain one or more elements of any data type. Arrays of user-defined and other data types are created using the Dim statement. Arrays of any type can be included within user-defined types.

variable

A named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its scope. A data type can be specified or not.

Variable names must begin with an alphabetic character, must be unique within the same scope, can't be longer than 255 characters, and can't contain an embedded period or type-declaration character.

Variant data type

A special data type that can contain numeric, string, or date data as well as user-defined types and the special values Empty and Null. The Variant data type has a numeric storage size of 16 bytes and can contain data up to the range of a Decimal, or a character storage size of 22 bytes (plus string length), and can store any character text. The VarType function defines how the data in a Variant is treated. All variables become Variant data types if not explicitly declared as some other data type.

variant expression

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

watch expression

A user-defined expression that enables you to observe the behavior of a variable or expression. Watch expressions appear in the Watch window of the Visual Basic Editor and are automatically updated when you enter break mode. The Watch window displays the value of an expression within a given context. Watch expressions are not saved with your code.

z-order

The visual layering of controls on a form along the form's z-axis (depth). The z-order determines which controls are in front of other controls.


Visual Basic how-to topics

 Copy code hover
[image]

Visual Basic how-to topics
Send feedback

In this section

  • Add a Watch Expression

  • Check or Add an Object Library Reference

  • Continue Code Execution

  • Copy Example Code from Help

  • Create a Procedure

  • Delete a Watch Expression

  • Edit a Watch Expression

  • Enter a Declaration in Code

  • Execute a Specific Statement

  • Find a Procedure

  • Find a Variable Definition

  • Import a Text File into Code

  • Replace Text in Code

  • Restart Execution

  • Search for Text in Code

  • Set and Clear a Breakpoint

  • Set Project Properties

  • Set Reference to a Type Library

  • Set Visual Basic Environment Options

  • Split the Code Window

  • Start Code Execution

  • Stop Code Execution

  • Trace Code Execution

  • Turn Syntax Checking On or Off

  • Use Quick Watch

  • Use the Immediate Window

  • Use the Object Browser

  • Use the Project Explorer

  • Use the Properties Window


Add a Watch Expression

 Copy code hover
[image]

Add a Watch Expression
Send feedback

A watch expression is an expression you define to be monitored in the Watch window. When your application enters break mode, the watch expressions you selected appear in the Watch window where you can observe their values.

To add a watch expression

  1. On the Debug menu, click Add Watch. The Add Watch dialog box is displayed.

  2. If an expression is already selected in the Code window, it is automatically displayed in the Expression box. If no expression is displayed, enter the expression you want to evaluate. The expression can be a variable, a property, a function call, or any other valid expression.

  3. Select a module or procedure context in the Context group to select the range for which the expression will be evaluated.

    Note Note

    Select the narrowest scope that fits your needs. Selecting all procedures or all modules can slow down module execution considerably, since the expression is evaluated after execution of each statement. If you select a specific procedure for a context, execution is affected only while the procedure is in the list of active procedure calls. Choose Call Stack from the View menu to display the list of active procedures.

  4. Select an option in the Watch Type group to define how the system responds to the watch expression.

    • To display the value of the watch expression, click Watch Expression.

    • To stop execution if the expression evaluates to True, click Break When Value is True.

    • To stop execution when the value of the expression changes, click Break When Value Changes.

  5. Click OK.


Check or Add an Object Library Reference

 Copy code hover
[image]

Check or Add an Object Library Reference
Send feedback

If you use the objects in other applications as part of your Visual Basic application, you may want to establish a reference to the object libraries of those applications. Before you can do that, you must first be sure that the application provides an object library.

To see if an application provides an object library

  1. From the Tools menu, choose References to display the References dialog box.

  2. The References dialog box shows all object libraries registered with the operating system. Scroll through the list for the application whose object library you want to reference. If the application isn't listed, you can use the Browse button to search for object libraries (*.olb and *.tlb) or executable files (*.exe and *.dll on Windows). References whose check boxes are checked are used by your project; those that aren't checked are not used, but can be added.

To add a object library reference to your project

  • Select the object library reference in the Available References box in the References dialog box and click OK. Your Visual Basic project now has a reference to the application's object library. If you open the Object Browser (press F2) and select the application's library, it displays the objects provided by the selected object library, as well as each object's methods and properties. In the Object Browser, you can select a class in the Classes box and select a method or property in the Members box. Use copy and paste to add the syntax to your code.


Continue Code Execution

 Copy code hover
[image]

Continue Code Execution
Send feedback

When you run your code, execution may stop if:

  • An untrapped run-time error occurs.

  • A trapped run-time error occurs, and Break on All Errors is selected on the General tab of the Options dialog box (Tools menu).

  • A previously set breakpoint is encountered.

  • A Stop statement in your code is encountered, switching the mode to break mode.

  • An End statement in your code is encountered, switching the mode to design time.

  • You halt execution manually at a given point.

  • A watch expression, which you set to break when the value has changed or break when the value is true, is encountered.

To halt execution manually

  1. To switch to break mode, choose Break (CTRL+BREAK) from the Run menu, or use the toolbar shortcut: .

  2. To switch to design time, choose Reset <projectname> from the Run menu, or use the toolbar shortcut: .

To continue execution when your application has halted

  • On the Run menu, click Continue (F5), or use the toolbar shortcut: . - Or -

  • On the Debug menu, click Step Into (F8), Step Over (SHIFT+F8), Step Out (CTRL+SHIFT+F8), or Run To Cursor (CTRL+F8)(.

To continue execution when your application has halted because of a handled error

  • Press ALT+F8 to step through the error-handler. - Or -

  • Press ALT+F5 to resume execution by running through the error-handler.


Copy Example Code from Help

 Copy code hover
[image]

Copy Example Code from Help
Send feedback

Sometimes you may want to copy a useful example from Visual Basic Help. While many of the examples require more code to work correctly, some examples are useful to see how a particular procedure or control flow technique behaves.

To copy example code from Help to your application

  1. Use Help to display the topic for the language element whose example you want to use.

  2. Click the Example link in the non-scrolling region near the top of the page. The code example is displayed.

  3. Right-click and select the part of the code you want to copy to your application. On the Macintosh, choose Copy from the Edit menu; a window appears in which you can select the code to copy.

  4. Choose Copy from the shortcut menu. On the Macintosh, press the Copy button.

  5. Move the focus back to the Code window and position the mouse pointer where you want the code example to be inserted.

  6. Right-click again and choose Paste to insert the code example into the Code window.

    Tip Tip

    You can also press CTRL+C to copy a selected example in a Help window. Press CTRL+V to paste the example into the Code window.


Create a Procedure

 Copy code hover
[image]

Create a Procedure
Send feedback

Code within a module is organized into procedures. A procedure tells the application how to perform a specific task. Use procedures to divide complex code tasks into more manageable units.

To create a procedure by writing code

  1. Open the module for which you want to write the procedure.

  2. You can create a Sub, Function, or Property procedure.

  3. Type Sub, Function, or Property. Press F1 to get Help with syntax, if necessary.

  4. Type code for the procedure. Visual Basic concludes the procedure with the appropriate End Sub, End Function, or End Property statement.

To create a procedure using the Insert Procedure dialog box

  1. Open the module for which you want to write the procedure.

  2. On the Insert menu, click Procedure.

  3. Type the name for the procedure in the Name box of the Insert Procedure dialog box.

  4. Select the type of procedure you want to create: Sub, Function, or Property.

  5. Set the procedure's scope to either Public or Private.

  6. You can select the All Local Variables as Statics to add the Static keyword to the procedure definition.

  7. Click OK.


Delete a Watch Expression

 Copy code hover
[image]

Delete a Watch Expression
Send feedback

To delete a watch expression in the Watch Window, do any of the following:

  • Select the watch expression and press DELETE.

  • Select the expression and choose Clear from the Edit menu.

  • Select the expression, choose Edit Watch from the Debug menu, and then press DELETE.

  • Right-click the expression and choose Delete Watch from the context menu.


Edit a Watch Expression

 Copy code hover
[image]

Edit a Watch Expression
Send feedback

To edit a watch expression

  1. Double-click the watch expression in the Watch window.

    -or-

    Select the expression and choose Edit Watch from the Debug menu.

    -or-

    Right-click the expression and choose Edit Watch from the context menu.

  2. Make any changes to the expression, the context, and the watch type.

  3. Click OK.


Enter a Declaration in Code

 Copy code hover
[image]

Enter a Declaration in Code
Send feedback

Declarations are nonexecutable code statements that name external procedures, constants, or variables and define their attributes (such as data type). You write declarations for form, standard, or class modules. To enter module-level declarations, go to the Declarations section of a module. To enter global declarations, go to the Declarations section of a module and use the Public statement for constants and variables. You can also use the Dim, Static, and Private keywords to make declarations.

You can also enter procedure-level declarations. For whatever code level and technique you use to declare a variable or constant, specific scoping rules may apply.

To open the Declarations section of a module

  1. In the Project window, select the form, standard, or class module you want to open and click the View Code button. - Or - Right-click and choose View Code from the context menu.

  2. Object box

    The Procedure box automatically displays (Declarations).

  3. Enter one or more declarations.


Execute a Specific Statement

 Copy code hover
[image]

Execute a Specific Statement
Send feedback

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. On the Debug menu, click Set Next Statement (CTRL+F9). - or on Windows - Position the mouse pointer in the margin indicator next to the current execution point.

  3. Drag the yellow arrow in the margin indicator to the statement you want to execute next.

    Note Note

    You can only skip to statements within the same procedure.

    Used in combination with Step Into, executing specific statements with the Set Next Statement command enables you to step through procedures one statement at a time, and to closely examine your code. It's also helpful for correcting or avoiding run-time error conditions.


Find a Procedure

 Copy code hover
[image]

Find a Procedure
Send feedback

To find a procedure in the Code window

  • To view an existing general procedure, select (General) in the Object box in the Code window, and then select the procedure in the Procedure box.

  • To view an event procedure, select the appropriate object in the Object box in the Code window, and then select the event in the Procedure box.

    Note Note

    To visually separate procedures in the Code window, you can select the Procedure Separator check box on the Editor tab of the Options dialog box (Tools menu). You can switch between Procedure view and Full Module view using the buttons in the lower-left corner of the Code window.

To find a procedure in another module

  1. On the View menu, click Object Browser, or press F2.

  2. Select the project in the Project/Library box.

  3. Select the module in the Classes list.

  4. Double-click the procedure name in the Members of list. The selected procedure is displayed in the Code window.

You can use the following 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 up through the procedures in your code.
F2 | Display the Object Browser.


Find a Variable Definition

 Copy code hover
[image]

Find a Variable Definition
Send feedback

To view the definition of a variable

  1. In the Code window, select the variable whose definition you want to see.

  2. From the View menu, choose Definition (SHIFT+F2).

To return the mouse pointer to its previous position

  • On the View menu, click Last Position (CTRL+SHIFT+F2).


Import a Text File into Code

 Copy code hover
[image]

Import a Text File into Code
Send feedback

You can import a text file containing code into the current module and use it in your code.

To import a text file into a module

  1. Open the module into which you want to insert text and position the entry point at the place where you want the text inserted.

  2. On the Insert menu, click File.

  3. The Insert File dialog box appears.

  4. Use the Insert File dialog box to select the file to import.

  5. Click OK.


Replace Text in Code

 Copy code hover
[image]

Replace Text in Code
Send feedback

To replace text in a module

  1. On the Edit menu, click Replace. The Replace dialog box appears.

  2. In the Find What box, type the text you want to search for.

  3. In the Replace With box, type the replacement text.

  4. Select a Search option to specify where to look for the text.

  5. Select a direction from the Direction list to specify the direction of the search.

  6. To set limits on the search, select:

    • Find Whole Word Only to search for the complete word by itself, and not as part of another word.

    • Match Case for an exact match.

    • Use Pattern Matching to use wildcard characters.

  7. Choose Find Next if you want to confirm the change before replacing the text; choose Replace to replace the highlighted occurrence of the found text and automatically perform a Find Next; or choose Replace All to change all occurrences of the search text automatically.


Restart Execution

 Copy code hover
[image]

Restart Execution
Send feedback

You can restart execution from break mode. Restarting returns the code to a newly initialized state, resetting all variables and removing any suspended procedures from memory.

To restart execution

  1. On the Run menu, click Reset <projectname>, or use the toolbar shortcut: .

  2. On the Run menu, click Run Sub/UserForm (F5), or use the toolbar shortcut: .


Search for Text in Code

 Copy code hover
[image]

Search for Text in Code
Send feedback

To search for specific text in a module

  1. On the Edit menu, click Find. The Find dialog box appears.

  2. In the Find What box, type the text you want to search for (if you didn't select the text before displaying the dialog box).

  3. Select a Search option to specify where to look for the text.

  4. Select a direction from Direction list to specify the direction of the search.

  5. To set limits on the search, select:

    • Find Whole Word Only to search for the complete word by itself and not as part of another word.

    • Match Case to find an exact match.

    • Use Pattern Matching to use wildcards or ranges.

  6. Choose Find Next.


Set and Clear a Breakpoint

 Copy code hover
[image]

Set and Clear a Breakpoint
Send feedback

You set a breakpoint to suspend execution at a specific statement in a procedure; for example, where you suspect problems may exist. You clear breakpoints when you no longer need them to stop execution.

To set a breakpoint

  1. Position the insertion point anywhere in a line of the procedure where you want execution to halt.

  2. On the Debug menu, click Toggle Breakpoint (F9), click next to the statement in the Margin Indicator Bar (if visible), or use the toolbar shortcut: . The breakpoint is added and the line is set to the breakpoint color defined on the Editor Format tab in the Options dialog box.

If you set a breakpoint on a line that contains several statements separated by colons (:), the break always occurs at the first statement on the line.

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 click next to the statement in the Margin Indicator Bar (if visible).

  3. The breakpoint is cleared and highlighting is removed.

To clear all breakpoints in the application

  • From the Debug menu, choose Clear All Breakpoints (CTRL+SHIFT+F9).

    Note Note

    Breakpoints set in code are not saved when you save your code.


Set Project Properties

 Copy code hover
[image]

Set Project Properties
Send feedback

To set Project Properties

  1. From the Tools menu, choose <projectname> Properties

  2. Use the General tab in the <projectname> Properties dialog box to specify the following:

    • Name of your project.

    • Description of your project.

    • Name of the Help file associated with your project.

    • Context ID for the specific Help topic to be called when the user clicks the Help button while the application's object library is selected in the Object Browser.

  3. Use the Protection tab in the <projectname> Properties dialog box to lock the project from viewing by others and specify a password for access to project properties. After you set protection, you must save and close your project for the protection to take effect.


Set Reference to a Type Library

 Copy code hover
[image]

Set Reference to a Type Library
Send feedback

Automation (formerly OLE Automation) enables you to use objects from other applications in Visual Basic code. An application that provides its objects for use by other applications also provides information about those objects in a type library. To achieve the best possible performance when using another application's objects, you should set a reference to that application's type library.

To set a reference to an application's type library

  1. Click References on the Tools menu.

  2. Select the check boxes for the applications with type libraries you want to reference.

If you are writing code that manipulates objects in another application, you should set a reference to that application's type library for best possible access to those objects. You don't have to set a reference to use another application's objects, but doing so provides several advantages for your application.

Your code will run faster if you set a reference to another application's type library before you work with its objects. If you set a reference, you can declare an object variable representing an object in the other application as its most specific type. For example, if you are writing code to work with Microsoft Excel objects, you can declare an object variable of type Excel.Application if you created a reference to the Microsoft Excel type library. The following code is the fastest way to create a variable to represent the Microsoft Excel Application object.

Copy code Copy code
Dim appXL As Excel.Application

If you haven't set a reference to the Microsoft Excel type library, you must declare the variable as a generic variable of type Object. The following code runs more slowly.

Copy code Copy code
Dim appXL As Object

If you set a reference to an application's type library, all of its objects and their methods and properties are listed in the Object Browser. This makes it easy to determine what properties and methods are available to each object.

For Microsoft applications that can also serve as Automation servers, you can set references to their type libraries from another application, and control their objects from that application.


Set Visual Basic Environment Options

 Copy code hover
[image]

Set Visual Basic Environment Options
Send feedback

You can set the behavior and look of the Visual Basic development environment through the Options dialog box. Use the:

  • Editor tab to specify Code window and Project window settings.

  • Editor Format tab to specify the appearance of your code.

  • General tab to specify form, error handling, and compile settings for your project.

  • Docking tab to specify whether a window is attached or "anchored" to one edge of other dockable or application windows.

To set Environment options

  • On the Tools menu of the Visual Basic editor, click Options. Each option is described in the following tables.

Editor

Option | Description
Auto Syntax Check | Visual Basic automatically verifies correct syntax after you enter a line of code.
Require Variable Declaration | Explicit variable declarations are required in modules.
Auto Indent | After tabbing the first line of code, all subsequent lines start at that tab location.
Tab Width | The tab width, which can range from 1 - 32 spaces. (Default is 4 spaces.)
Default to Full Module View | Procedures for new modules are displayed in the Code window as a single, scrollable list or one procedure at a time.
Procedure Separator | Display separator bars at the end of each procedure in the Code window.
Auto List Members | At the insertion point, Visual Basic displays information that logically completes a statement.
Auto Quick Info | Information about functions and their arguments is displayed as you type.
Auto Data Tips | Automatically display the value of any variable on which you place the mouse pointer. Available only in break mode.
Drag-Drop in Text Editing | Code elements can be dragged from the Code window into the Immediate or Watch windows.

Editor Format

Option | Description
Foreground, Background, and Indicator | The color of different categories of text listed in the Code Colors list.
Font | The font used for displaying code.
Size | The size of the font used for code.
Margin Indicator Bar | Display the Margin Indicator Bar.

General

Option | Description
Show Grid | Display a grid on a form.
Grid Units | Lists the unit of measurement for units in the grid.
Width | The width of the grid cells on a form.
Height | The height of the grid cells on a form.
Align Controls to Grid | Automatically position the outer edge of controls on the closest grid lines.
Show ToolTips | Display ToolTips for toolbar buttons.
Collapse Proj. Hides Windows | Automatically close the project, UserForm, object, or module windows when a project is collapsed in the Project Explorer.
Notify Before State Loss | Display a message that a requested action will cause all module-level variables to be reset for a running project.
Break on All Errors | Any error causes the project to enter break mode, whether or not an error handler is active, and whether or not the code is in a class module.
Break in Class Module | Any unhandled error produced in a class module causes the project to enter break mode at the line of code which produced the error.
Break on Unhandled Errors | Any other unhandled error causes the project to enter break mode.
Compile On Demand | A project is fully compiled before it starts, or code is compiled as needed.
Background Compile | Use idle time during run time to finish compiling the project in the background. (Available only if Compile On Demand is set.)

Docking

Option | Description
The check box for the appropriate window | A window can be anchored to an adjacent dockable window or the Visual Basic Editor window.


Split the Code Window

 Copy code hover
[image]

Split the Code Window
Send feedback

You can split the Code window horizontally into two panes to view different code segments of a module at the same time. Each pane scrolls separately, both horizontally and vertically. The Procedure and Object box options refer to the pane that has the focus. Code changes are immediately reflected in both panes.

To split the Code window into panes

  • Drag the split bar at the top of the vertical scroll bar down from the upper-right corner of the Code window.

To remove a split from the Code window

  • Double-click the split bar or drag it to the top or bottom of the Code window.


Start Code Execution

 Copy code hover
[image]

Start Code Execution
Send feedback

One way to test your code is to run it and work with it as a user would.

To start code execution

  • Choose Run Sub/UserForm (F5) from the Run menu.

If your application doesn't run, it may be because:

  • A syntax error or some other error exists in your code.

  • A logic error exists in your code, which may result in a run-time error.

To get Help, click the Help button or press F1 while the error message is displayed. Consider the suggestions provided to correct the error before you run your code again.


Stop Code Execution

 Copy code hover
[image]

Stop Code Execution
Send feedback

As you run your code, it may stop executing for one of the following reasons:

  • An untrapped run-time error occurs.

  • A trapped run-time error occurs, and Break on All Errors is selected on the General tab in the Options dialog box.

  • A breakpoint is encountered.

  • A Stop statement is encountered in your code, switching the mode to break mode.

  • An End statement is encountered in your code, switching the mode to design time.

  • You halt execution manually at a given point.

  • A watch expression that you set to break if its value changes or becomes true is encountered.

To halt execution manually

  • To switch to break mode, from the Run menu, choose Break (CTRL+BREAK), or use the toolbar shortcut: .

  • To switch to design time, from the Run menu, choose Reset <projectname>, or use the toolbar shortcut: .

To continue execution when your application has halted

  • From the Debug menu, choose Step Into (F8), Step Over (SHIFT+F8), Step Out (CTRL+SHIFT+F8), or Run To Cursor (CTRL+F8.


Trace Code Execution

 Copy code hover
[image]

Trace Code Execution
Send feedback

You trace code execution because it may not always be obvious which statement is executed first. Use these techniques to trace the execution of code:

  • Step Into: Traces through each line of code and steps into procedures. This allows you to view the effect of each statement on variables.

  • Step Over: Executes each procedure as if it were a single statement. Use this instead of Step Into to step across procedure calls rather than into the called procedure.

  • Step Out: Executes all remaining code in a procedure as if it were a single statement, and exits to the next statement in the procedure that caused the procedure to be called initially.

  • Run To Cursor: Allows you to select a statement in your code where you want execution to stop. This allows you to "step over" sections of code, for example, large loops.

To trace execution from the current statement

  • From the Debug menu, choose Step Into (F8), Step Over (SHIFT+F8), Step Out (CTRL+SHIFT+F8), or Run To Cursor (CTRL+F8).

To trace execution from the beginning of the program

  • From the Debug menu, choose Step Into (F8), Step Over (SHIFT+F8), Step Out (CTRL+SHIFT+F8), or Run To Cursor (CTRL+F8).


Turn Syntax Checking On or Off

 Copy code hover
[image]

Turn Syntax Checking On or Off
Send feedback

Visual Basic includes a syntax-checking feature that:

  • Checks each statement as you enter it for syntax errors, such as a misspelled keyword or missing separator, and alerts you if there are errors.

  • Translates the code to an internal form if the syntax is correct, which speeds the transition to run time.

This feature is turned on when you first start, but you can turn it off if you prefer to write code without being alerted to errors as they occur.

To enable syntax checking

  1. On the Tools menu, click Options.

  2. Select the Editor tab.

  3. Select the Auto Syntax Check check box.

  4. Click OK.

To disable syntax checking

  1. Click Options on the Tools menu.

  2. Select the Editor tab.

  3. Clear the Auto Syntax Check check box.

  4. Click OK.


Use Quick Watch

 Copy code hover
[image]

Use Quick Watch
Send feedback

In break mode, you may want to check the current value of a variable or expression for which you haven't defined a watch expression. Do this using the Quick Watch command.

To display a Quick Watch

  1. Select an expression in the module where it resides.

  2. From the Debug menu, choose Quick Watch (SHIFT+F9). The Quick Watch dialog box displays the current value of the expression you selected. -or- Right-click and choose Quick Info from the context menu. The data type of the expression is displayed.

  3. To add a watch expression based on the expression in the Quick Watch dialog box, choose Add.


Use the Immediate Window

 Copy code hover
[image]

Use the Immediate Window
Send feedback

The Immediate window displays information resulting from debugging statements in your code or from commands typed directly into the window.

To display the Immediate window

  • From the View menu, choose Immediate window (CTRL+G)

To execute code in the Immediate window

  1. Type a line of code in the Immediate window.

  2. Press ENTER to execute the statement.

Use the Immediate window to:

  • Test problematic or newly written code.

  • Query or change the value of a variable while running an application. While execution is halted, assign the variable a new value as you would in code.

  • Query or change a property value while running an application.

  • Call procedures as you would in code.

  • View debugging output while the program is running.

    Note Note

    Immediate window statements are executed in a context — that is, as if they are entered in a specific module.

If you need help on syntax for functions, statements, properties, or methods while working in the Immediate window, select the keyword, the property name, or the method name, and press F1.


Use the Object Browser

 Copy code hover
[image]

Use the Object Browser
Send feedback

The Object Browser allows you to browse through all available objects in your project and see their properties, methods and events. In addition, you can see the procedures and constants that are available from object libraries in your project. You can easily display online Help as you browse. You can use the Object Browser to find and use objects you create, as well as objects from other applications.

You can get help for the Object Browser by searching for Object Browser in Help.

To navigate the Object Browser

  1. Activate a module.

  2. From the View menu, choose Object Browser (F2), or use the toolbar shortcut: .

  3. Select the name of the project or library you want to view in the Project/Library list.

  4. Use the Class list to select the class; use the Member list to select specific members of your class or project.

  5. View information about the class or member you selected in the Details section at the bottom of the window.

  6. Use the Help button to display the Help topic for the class or member you selected.


Use the Project Explorer

 Copy code hover
[image]

Use the Project Explorer
Send feedback

The Project Explorer displays a hierarchical list of the projects and all of the items contained and referenced by each project.

To navigate the Project Explorer

  1. From the View menu, choose Project Explorer (CTRL+R), or use the toolbar shortcut: .

  2. Select an item from the collapsible tree that includes all projects and their components.

  3. Click the View Code button to open the Code window to begin entering code. - or - Click the View Object button to open a window containing the specified object. - or - Click the Toggle Folders button to toggle between folder view and folder contents view.


Use the Properties Window

 Copy code hover
[image]

Use the Properties Window
Send feedback

The Properties window lists the design-time properties for selected objects and their current settings. You can change these properties at design time. When you select multiple controls, the Properties window contains a list of the properties common to all the selected controls.

To navigate the Properties window

  1. From the View menu of the Visual Basic Editor, choose Properties window (F4).

  2. Select the object whose properties you want to display. You can either use the mouse to select the object or use the Project Explorer to choose from a list.

  3. Click the Alphabetic tab to display properties in alphabetic order, or click the Categorized tab to display object properties by category.

To change a property's value

  1. Select the property in the left column.

  2. Change the property's value in the right column.

    Note Note

    You can enter a property's value in the right column. For those properties that have a predefined set of values, click the value and then select one from the values displayed in the list box.


Visual Basic language reference

 Copy code hover
[image]

Visual Basic language reference
Send feedback

In this section

  • Ambiguous selection

  • Keyword Not Found

  • Character Sets

  • Constants (Visual Basic for Applications)

  • Data Types

  • Directives

  • Error Messages

  • Events (Visual Basic for Applications)

  • Functions (Visual Basic for Applications)

  • Keywords (Visual Basic for Applications)

  • Keyword Summaries

  • Methods (Visual Basic for Applications)

  • Object Browser (Visual Basic for Applications)

  • Objects (Visual Basic for Applications)

  • Operators

  • Properties (Visual Basic for Applications)

  • Statements

  • Strings


Ambiguous selection

 Copy code hover
[image]

Ambiguous selection
Send feedback

Either you have not selected a keyword or you have requested Help on a component of the integrated development environment (IDE). If you were trying to select a keyword, try reselecting a single keyword. If you were trying to get information on the IDE, click one of the following:

Code or Module Window

Immediate Window or Pane

Locals Windows or Pane

Object Browser

Watch Window or Pane


Keyword Not Found

 Copy code hover
[image]

Keyword Not Found
Send feedback

The keyword you selected can't be found in Visual Basic Help. You may have misspelled the keyword, selected too much or too little text, or asked for help on a word that isn't a valid Visual Basic keyword.

The keyword you want help on may be contained within an object library that is not referenced. Make sure references are set to the appropriate object libraries for all objects used in your code.

The easiest way to get help on a specific keyword is to position the insertion point anywhere within the keyword and press F1. You don't have to select the keyword. In fact, if you select only a portion of the keyword, or more than a single word, Help won't find what you're looking for.

The Value property topic is displayed when you press F1 with the insertion point between the "a" and the "l" in the Value keyword as shown in the following example.

Copy code Copy code
Worksheets(1).Range ("A2").value=3.14159

To use the built-in Help Search, click Microsoft Visual Basic Help on the Help menu.


Character Sets

 Copy code hover
[image]

Character Sets
Send feedback

In this section

  • Character Set (0 - 127)

  • Character Set (128 - 255)


Character Set (0 - 127)

 Copy code hover
[image]

Character Set (0 - 127)
Send feedback
0 |  | 32 | [space] | 64 | @ | 96 | `
1 |  | 33 | ! | 65 | A | 97 | a
2 |  | 34 | " | 66 | B | 98 | b
3 |  | 35 | # | 67 | C | 99 | c
4 |  | 36 | $ | 68 | D | 100 | d
5 |  | 37 | % | 69 | E | 101 | e
6 |  | 38 | & | 70 | F | 102 | f
7 |  | 39 | ' | 71 | G | 103 | g
8 | * * | 40 | ( | 72 | H | 104 | h
9 | * * | 41 | ) | 73 | I | 105 | i
10 | * * | 42 | * | 74 | J | 106 | j
11 |  | 43 | + | 75 | K | 107 | k
12 |  | 44 | , | 76 | L | 108 | l
13 | * * | 45 | - | 77 | M | 109 | m
14 |  | 46 | . | 78 | N | 110 | n
15 |  | 47 | / | 79 | O | 111 | o
16 |  | 48 | 0 | 80 | P | 112 | p
17 |  | 49 | 1 | 81 | Q | 113 | q
18 |  | 50 | 2 | 82 | R | 114 | r
19 |  | 51 | 3 | 83 | S | 115 | s
20 |  | 52 | 4 | 84 | T | 116 | t
21 |  | 53 | 5 | 85 | U | 117 | u
22 |  | 54 | 6 | 86 | V | 118 | v
23 |  | 55 | 7 | 87 | W | 119 | w
24 |  | 56 | 8 | 88 | X | 120 | x
25 |  | 57 | 9 | 89 | Y | 121 | y
26 |  | 58 | : | 90 | Z | 122 | z
27 |  | 59 | ; | 91 | [ | 123 | {
28 |  | 60 | < | 92 | \ | 124 | |
29 |  | 61 | = | 93 | ] | 125 | }
30 |  | 62 | > | 94 | ^ | 126 | ~
31 |  | 63 | ? | 95 | _ | 127 | 

These characters aren't supported by Microsoft Windows.

* *Values 8, 9, 10, and 13 convert to backspace, tab, linefeed, and carriage return characters, respectively. They have no graphical representation but, depending on the application, can affect the visual display of text.


Character Set (128 - 255)

 Copy code hover
[image]

Character Set (128 - 255)
Send feedback
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.

The values in the table are the Windows default. However, values in the ANSI character set above 127 are determined by the code page specific to your operating system.


Constants (Visual Basic for Applications)

 Copy code hover
[image]

Constants (Visual Basic for Applications)
Send feedback

In this section

  • Visual Basic Constants

  • Calendar Constants

  • CallType Constants

  • Color Constants

  • ColorConstants (Object Browser)

  • Comparison Constants

  • Compiler Constants

  • Date Constants

  • Date Format Constants

  • Dir, GetAttr, and SetAttr Constants

  • DriveType Constants

  • File Attribute Constants

  • File Input/Output Constants

  • Form Constants

  • FormShowConstants (Object Browser)

  • IMEStatus Constants

  • Keycode Constants

  • KeycodeConstants (Object Browser)

  • Miscellaneous Constants

  • MsgBox Constants

  • QueryClose Constants

  • Shell Constants

  • SpecialFolder Constants

  • StrConv Constants

  • System Color Constants

  • SystemColorConstants (Object Browser)

  • Tristate Constants

  • VarType Constants


Visual Basic Constants

 Copy code hover
[image]

Visual Basic Constants
Send feedback

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

Calendar Constants

CallType Constants

Color Constants

Comparison Constants

Compiler Constants

Date Constants

Date Format Constants

Dir, GetAttr, and SetAttr Constants

DriveType Constants

File Attribute Constants

File Input/Output Constants

Form Constants

IMEStatus Constants

Keycode Constants

Miscellaneous Constants

MsgBox Constants

QueryClose Constants

Shell Constants

SpecialFolder Constants

StrConv Constants

System Color Constants

Tristate Constants

VarType Constants

Visual Basic Constants


Calendar Constants

 Copy code hover
[image]

Calendar Constants
Send feedback

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

Constant | Value | Description
vbCalGreg | 0 | Indicates that the Gregorian calendar is used.
vbCalHijri | 1 | Indicates that the Hijri calendar is used.


CallType Constants

 Copy code hover
[image]

CallType Constants
Send feedback

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

Constant | Value | Decription
vbMethod | 1 | Indicates that a method has been invoked.
vbGet | 2 | Indicates a Property Get procedure.
vbLet | 4 | Indicates a Property Let procedure.
vbSet | 8 | Indicates a Property Set procedure.


Color Constants

 Copy code hover
[image]

Color Constants
Send feedback

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

Constant | Value | Description
vbBlack | 0x0 | Black
vbRed | 0xFF | Red
vbGreen | 0xFF00 | Green
vbYellow | 0xFFFF | Yellow
vbBlue | 0xFF0000 | Blue
vbMagenta | 0xFF00FF | Magenta
vbCyan | 0xFFFF00 | Cyan
vbWhite | 0xFFFFFF | White


ColorConstants (Object Browser)

 Copy code hover
[image]

ColorConstants (Object Browser)
Send feedback

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

To get Help on a particular constant

  1. Select the constant from the Members of 'ColorConstants' list.

  2. Click the [image] button.


Comparison Constants

 Copy code hover
[image]

Comparison Constants
Send feedback

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

Constant | Value | Description
vbUseCompareOption | -1 | Performs a comparison using the setting of the Option Compare statement.
vbBinaryCompare | 0 | Performs a binary comparison.
vbTextCompare | 1 | Performs a textual comparison.
vbDatabaseCompare | 2 | For Microsoft Access (Windows only), performs a comparison based on information contained in your database.


Compiler Constants

 Copy code hover
[image]

Compiler Constants
Send feedback

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

Note Note

Because Win32 returns true in both 32-bit and 64-bit development platforms it is important that the order within the #If...Then...#Else directive returns the desired results in your code. For example, because Win32 returns True in 64-bit (Win32 is compatible in Win64 environments) checking for Win32 before Win64 results in the Win64 condition never running because Win32 returns True. The following order returns predictable results:
VBA Copy code Copy code
#If Win64 Then
' Win64=true, Win32=true, Win16= false
#ElseIf Win32 Then
' Win32=true, Win16=false
#Else
' Win16=true
#End If

This applies to both Winx and VBAx constants.

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

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

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

Constant | Value | Description
Vba6 | True | Indicates that the development environment is Visual Basic for Applications, version 6.0 compatible.
Vba6 | False | Indicates that the development environment is not Visual Basic for Applications, version 6.0 compatible.
Vba7 | True | Indicates that the development environment is Visual Basic for Applications, version 7.0 compatible.
Vba7 | False | Indicates that the development environment is not Visual Basic for Applications, version 7.0 compatible.
Win16 | False | Indicates that the development environment is not 16-bit compatible.
Win32 | True | Indicates that the development environment is 32-bit compatible.
Win64 | False | Indicates that the development environment is not 64-bit compatible.
Mac | True | Indicates that the development environment is Macintosh.
Mac | False | Indicates that the development environment is not Macintosh.

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

Constant | Value | Description
Vba6 | True | Indicates that the development environment is Visual Basic for Applications, version 6.0 compatible.
Vba6 | False | Indicates that the development environment is not Visual Basic for Applications, version 6.0 compatible.
Vba7 | True | Indicates that the development environment is Visual Basic for Applications, version 7.0 compatible.
Vba7 | False | Indicates that the development environment is not Visual Basic for Applications, version 7.0 compatible.
Win16 | False | Indicates development environment is not 16-bit compatible.
Win32 | True | Indicates that the development environment is 32-bit compatible.
Win64 | True | Indicates that the development environment is 64-bit compatible.
Mac | True | Indicates that the development environment is Macintosh.
Mac | False | Indicates that the development environment is not Macintosh.
Note Note

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


Date Constants

 Copy code hover
[image]

Date Constants
Send feedback

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

Argument Values

The firstdayofweek argument has the following values:

Constant | Value | Description
vbUseSystem | 0 | Use NLS API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

The firstdayofyear argument has the following values:

Constant | Value | Description
vbUseSystem | 0 | Use NLS API setting.
VbUseSystem DayOfWeek | 0 | Use the day of the week specified in your system settings for the first day of the week.
VbFirstJan1 | 1 | Start with week in which January 1 occurs (default).
vbFirstFourDays | 2 | Start with the first week that has at least four days in the new year.
vbFirstFullWeek | 3 | Start with the first full week of the year.

Return Values

Constant | Value | Description
vbSunday | 1 | Sunday
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday


Date Format Constants

 Copy code hover
[image]

Date Format Constants
Send feedback

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

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


Dir, GetAttr, and SetAttr Constants

 Copy code hover
[image]

Dir, GetAttr, and SetAttr Constants
Send feedback

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

Constant | Value | Description
vbNormal | 0 | Normal (default for Dir and SetAttr)
vbReadOnly | 1 | Read-only
vbHidden | 2 | Hidden
vbSystem | 4 | System file
vbVolume | 8 | Volume label
vbDirectory | 16 | Directory or folder
vbArchive | 32 | File has changed since last backup
vbAlias | 64 | On the Macintosh, identifier is an alias.

Only VbNormal, vbReadOnly, vbHidden, and vbAlias are available on the Macintosh.


DriveType Constants

 Copy code hover
[image]

DriveType Constants
Send feedback

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

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


File Attribute Constants

 Copy code hover
[image]

File Attribute Constants
Send feedback

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

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


File Input/Output Constants

 Copy code hover
[image]

File Input/Output Constants
Send feedback

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

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


Form Constants

 Copy code hover
[image]

Form Constants
Send feedback

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

Constant | Value | Decription
vbModeless | 0 | UserForm is modeless.
vbModal | 1 | UserForm is modal (default).


FormShowConstants (Object Browser)

 Copy code hover
[image]

FormShowConstants (Object Browser)
Send feedback

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

To get Help on a particular constant

  1. Select the constant from the Members of 'FormShowConstants' list.

  2. Click the [image] button.


IMEStatus Constants

 Copy code hover
[image]

IMEStatus Constants
Send feedback

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

The constants for the Japanese locale are as follows:

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

The constant values for the Korean locale are as follows:

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

The constant values for the Chinese locale are as follows:

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


Keycode Constants

 Copy code hover
[image]

Keycode Constants
Send feedback

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

Constant | Value | Description
vbKeyLButton | 0x1 | Left mouse button
vbKeyRButton | 0x2 | Right mouse button
vbKeyCancel | 0x3 | CANCEL key
vbKeyMButton | 0x4 | Middle mouse button
vbKeyBack | 0x8 | BACKSPACE key
vbKeyTab | 0x9 | TAB key
vbKeyClear | 0xC | CLEAR key
vbKeyReturn | 0xD | ENTER key
vbKeyShift | 0x10 | SHIFT key
vbKeyControl | 0x11 | CTRL key
vbKeyMenu | 0x12 | MENU key
vbKeyPause | 0x13 | PAUSE key
vbKeyCapital | 0x14 | CAPS LOCK key
vbKeyEscape | 0x1B | ESC key
vbKeySpace | 0x20 | SPACEBAR key
vbKeyPageUp | 0x21 | PAGE UP key
vbKeyPageDown | 0x22 | PAGE DOWN key
vbKeyEnd | 0x23 | END key
vbKeyHome | 0x24 | HOME key
vbKeyLeft | 0x25 | LEFT ARROW key
vbKeyUp | 0x26 | UP ARROW key
vbKeyRight | 0x27 | RIGHT ARROW key
vbKeyDown | 0x28 | DOWN ARROW key
vbKeySelect | 0x29 | SELECT key
vbKeyPrint | 0x2A | PRINT SCREEN key
vbKeyExecute | 0x2B | EXECUTE key
vbKeySnapshot | 0x2C | SNAPSHOT key
vbKeyInsert | 0x2D | INSERT key
vbKeyDelete | 0x2E | DELETE key
vbKeyHelp | 0x2F | HELP key
vbKeyNumlock | 0x90 | NUM LOCK key

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

Constant | Value | Description
vbKeyA | 65 | A key
vbKeyB | 66 | B key
vbKeyC | 67 | C key
vbKeyD | 68 | D key
vbKeyE | 69 | E key
vbKeyF | 70 | F key
vbKeyG | 71 | G key
vbKeyH | 72 | H key
vbKeyI | 73 | I key
vbKeyJ | 74 | J key
vbKeyK | 75 | K key
vbKeyL | 76 | L key
vbKeyM | 77 | M key
vbKeyN | 78 | N key
vbKeyO | 79 | O key
vbKeyP | 80 | P key
vbKeyQ | 81 | Q key
vbKeyR | 82 | R key
vbKeyS | 83 | S key
vbKeyT | 84 | T key
vbKeyU | 85 | U key
vbKeyV | 86 | V key
vbKeyW | 87 | W key
vbKeyX | 88 | X key
vbKeyY | 89 | Y key
vbKeyZ | 90 | Z key

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

Constant | Value | Description
vbKey0 | 48 | 0 key
vbKey1 | 49 | 1 key
vbKey2 | 50 | 2 key
vbKey3 | 51 | 3 key
vbKey4 | 52 | 4 key
vbKey5 | 53 | 5 key
vbKey6 | 54 | 6 key
vbKey7 | 55 | 7 key
vbKey8 | 56 | 8 key
vbKey9 | 57 | 9 key

The following constants represent keys on the numeric keypad:

Constant | Value | Description
vbKeyNumpad0 | 0x60 | 0 key
vbKeyNumpad1 | 0x61 | 1 key
vbKeyNumpad2 | 0x62 | 2 key
vbKeyNumpad3 | 0x63 | 3 key
vbKeyNumpad4 | 0x64 | 4 key
vbKeyNumpad5 | 0x65 | 5 key
vbKeyNumpad6 | 0x66 | 6 key
vbKeyNumpad7 | 0x67 | 7 key
vbKeyNumpad8 | 0x68 | 8 key
vbKeyNumpad9 | 0x69 | 9 key
vbKeyMultiply | 0x6A | MULTIPLICATION SIGN (*) key
vbKeyAdd | 0x6B | PLUS SIGN (+) key
vbKeySeparator | 0x6C | ENTER key
vbKeySubtract | 0x6D | MINUS SIGN (-) key
vbKeyDecimal | 0x6E | DECIMAL POINT (.) key
vbKeyDivide | 0x6F | DIVISION SIGN (/) key

The following constants represent function keys:

Constant | Value | Description
vbKeyF1 | 0x70 | F1 key
vbKeyF2 | 0x71 | F2 key
vbKeyF3 | 0x72 | F3 key
vbKeyF4 | 0x73 | F4 key
vbKeyF5 | 0x74 | F5 key
vbKeyF6 | 0x75 | F6 key
vbKeyF7 | 0x76 | F7 key
vbKeyF8 | 0x77 | F8 key
vbKeyF9 | 0x78 | F9 key
vbKeyF10 | 0x79 | F10 key
vbKeyF11 | 0x7A | F11 key
vbKeyF12 | 0x7B | F12 key
vbKeyF13 | 0x7C | F13 key
vbKeyF14 | 0x7D | F14 key
vbKeyF15 | 0x7E | F15 key
vbKeyF16 | 0x7F | F16 key


KeycodeConstants (Object Browser)

 Copy code hover
[image]

KeycodeConstants (Object Browser)
Send feedback

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

To get Help on a particular constant

  1. Select the constant from the Members of 'KeyCodeConstants' list.

  2. Click the [image] button.


Miscellaneous Constants

 Copy code hover
[image]

Miscellaneous Constants
Send feedback

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

Constant | Equivalent | Description
vbCrLf | Chr(13) + Chr(10) | Carriage return-linefeed combination
vbCr | Chr(13) | Carriage return character
vbLf | Chr(10) | Linefeed character
vbNewLine | Chr(13) + Chr(10) or, on the Macintosh, Chr(13) | Platform-specific new line character; whichever is appropriate for current platform
vbNullChar | Chr(0) | Character having value 0
vbNullString | String having value 0 | Not the same as a zero-length string (""); used for calling external procedures
vbObjectError | -2147221504 | User-defined error numbers should be greater than this value. For example: Err.Raise Number = vbObjectError + 1000
vbTab | Chr(9) | Tab character
vbBack | Chr(8) | Backspace character
vbFormFeed | Chr(12) | Not useful in Microsoft Windows or on the Macintosh
vbVerticalTab | Chr(11) | Not useful in Microsoft Windows or on the Macintosh


MsgBox Constants

 Copy code hover
[image]

MsgBox Constants
Send feedback

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

MsgBox Arguments

Constant | Value | Description
vbOKOnly | 0 | OK button only (default)
vbOKCancel | 1 | OK and Cancel buttons
vbAbortRetryIgnore | 2 | Abort, Retry, and Ignore buttons
vbYesNoCancel | 3 | Yes, No, and Cancel buttons
vbYesNo | 4 | Yes and No buttons
vbRetryCancel | 5 | Retry and Cancel buttons
vbCritical | 16 | Critical message
vbQuestion | 32 | Warning query
vbExclamation | 48 | Warning message
vbInformation | 64 | Information message
vbDefaultButton1 | 0 | First button is default (default)
vbDefaultButton2 | 256 | Second button is default
vbDefaultButton3 | 512 | Third button is default
vbDefaultButton4 | 768 | Fourth button is default
vbApplicationModal | 0 | Application modal message box (default)
vbSystemModal | 4096 | System modal message box
vbMsgBoxHelpButton | 16384 | Adds Help button to the message box
VbMsgBoxSetForeground | 65536 | Specifies the message box window as the foreground window
vbMsgBoxRight | 524288 | Text is right aligned
vbMsgBoxRtlReading | 1048576 | Specifies text should appear as right-to-left reading on Hebrew and Arabic systems

MsgBox Return Values

Constant | Value | Description
vbOK | 1 | OK button pressed
vbCancel | 2 | Cancel button pressed
vbAbort | 3 | Abort button pressed
vbRetry | 4 | Retry button pressed
vbIgnore | 5 | Ignore button pressed
vbYes | 6 | Yes button pressed
vbNo | 7 | No button pressed


QueryClose Constants

 Copy code hover
[image]

QueryClose Constants
Send feedback

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

Constant | Value | Description
vbFormControlMenu | 0 | The user chose the Close command from the Control menu on the form.
vbFormCode | 1 | The Unload statement is invoked from code.
vbAppWindows | 2 | The current Microsoft Windows operating environment session is ending.
vbAppTaskManager | 3 | The Windows Task Manager is closing the application.


Shell Constants

 Copy code hover
[image]

Shell Constants
Send feedback

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

Constant | Value | Description
vbHide | 0 | Window is hidden and focus is passed to the hidden window.
vbNormalFocus | 1 | Window has focus and is restored to its original size and position.
vbMinimizedFocus | 2 | Window is displayed as an icon with focus.
vbMaximizedFocus | 3 | Window is maximized with focus.
vbNormalNoFocus | 4 | Window is restored to its most recent size and position. The currently active window remains active.
vbMinimizedNoFocus | 6 | Window is displayed as an icon. The currently active window remains active.

On the Macintosh, vbNormalFocus, vbMinimizedFocus, and vbMaximizedFocus all place the application in the foreground; vbHide, vbNoFocus, vbMinimizedFocus all place the application in the background.


SpecialFolder Constants

 Copy code hover
[image]

SpecialFolder Constants
Send feedback

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

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


StrConv Constants

 Copy code hover
[image]

StrConv Constants
Send feedback

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

Constant | Value | Description
vbUpperCase | 1 | Converts the string to uppercase characters.
vbLowerCase | 2 | Converts the string to lowercase characters.
vbProperCase | 3 | Converts the first letter of every word in string to uppercase.
vbWide | 4 | Converts narrow (single-byte) characters in string to wide (double-byte) characters. Applies to East Asia locales.
vbNarrow | 8 | Converts wide (double-byte) characters in string to narrow (single-byte) characters. Applies to East Asia locales.
vbKatakana | 16 | Converts Hiragana characters in string to Katakana characters. Applies to Japan only.
vbHiragana | 32 | Converts Katakana characters in string to Hiragana characters. Applies to Japan only.
vbUnicode | 64 | Converts the string to Unicode using the default code page of the system. (Not available on the Macintosh.)
vbFromUnicode | 128 | Converts the string from Unicode to the default code page of the system. (Not available on the Macintosh.)


System Color Constants

 Copy code hover
[image]

System Color Constants
Send feedback

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

Constant | Value | Description
vbScrollBars | 0x80000000 | Scroll bar color
vbDesktop | 0x80000001 | Desktop color
vbActiveTitleBar | 0x80000002 | Color of the title bar for the active window
vbInactiveTitleBar | 0x80000003 | Color of the title bar for the inactive window
vbMenuBar | 0x80000004 | Menu background color
vbWindowBackground | 0x80000005 | Window background color
vbWindowFrame | 0x80000006 | Window frame color
vbMenuText | 0x80000007 | Color of text on menus
vbWindowText | 0x80000008 | Color of text in windows
vbTitleBarText | 0x80000009 | Color of text in caption, size box, and scroll arrow
vbActiveBorder | 0x8000000A | Border color of active window
vbInactiveBorder | 0x8000000B | Border color of inactive window
vbApplicationWorkspace | 0x8000000C | Background color of multiple-document interface (MDI) applications
vbHighlight | 0x8000000D | Background color of items selected in a control
vbHighlightText | 0x8000000E | Text color of items selected in a control
vbButtonFace | 0x8000000F | Color of shading on the face of command buttons
vbButtonShadow | 0x80000010 | Color of shading on the edge of command buttons
vbGrayText | 0x80000011 | Grayed (disabled) text
vbButtonText | 0x80000012 | Text color on push buttons
vbInactiveCaptionText | 0x80000013 | Color of text in an inactive caption
vb3DHighlight | 0x80000014 | Highlight color for 3-D display elements
vb3DDKShadow | 0x80000015 | Darkest shadow color for 3-D display elements
vb3DLight | 0x80000016 | Second lightest 3-D color after vb3DHighlight
vbInfoText | 0x80000017 | Color of text in ToolTips
vbInfoBackground | 0x80000018 | Background color of ToolTips


SystemColorConstants (Object Browser)

 Copy code hover
[image]

SystemColorConstants (Object Browser)
Send feedback

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

To get Help on a particular constant

  1. Select the constant from the Members of 'SystemColorConstants' list.

  2. Click the [image] button.


Tristate Constants

 Copy code hover
[image]

Tristate Constants
Send feedback

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

Constant | Value | Description
vbTrue | -1 | True
vbFalse | ;0 | False
vbUseDefault | -2 | Use default setting


VarType Constants

 Copy code hover
[image]

VarType Constants
Send feedback

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

Constant | Value | Description
vbEmpty | 0 | Uninitialized (default)
vbNull | 1 | Contains no valid data
vbInteger | 2 | Integer
vbLong | 3 | Long integer
vbSingle | 4 | Single-precision floating-point number
vbDouble | 5 | Double-precision floating-point number
vbCurrency | 6 | Currency
vbDate | 7 | Date
vbString | 8 | String
vbObject | 9 | Object
vbError | 10 | Error
vbBoolean | 11 | Boolean
vbVariant | 12 | Variant (used only for arrays of variants)
vbDataObject | 13 | Data access object
vbDecimal | 14 | Decimal
vbByte | 17 | Byte
vbLongLong | 20 | LongLong integer (Valid on 64-bit platforms only.)
vbUserDefinedType | 36 | Variants that contain user-defined types
vbArray | 8192 | Array


Data Types

 Copy code hover
[image]

Data Types
Send feedback

In this section

  • Data Type Summary

  • Boolean Data Type

  • Byte Data Type

  • Currency Data Type

  • Date Data Type

  • Decimal Data Type

  • Double Data Type

  • Integer Data Type

  • Long Data Type

  • LongLong Data Type

  • LongPtr Data Type

  • Object Data Type

  • Single Data Type

  • String Data Type

  • User-Defined Data Type

  • Variant Data Type


Data Type Summary

 Copy code hover
[image]

Data Type Summary
Send feedback

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

Data type | Storage size | Range
Byte | 1 byte | 0 to 255
Boolean | 2 bytes | True or False
Integer | 2 bytes | -32,768 to 32,767
Long (long integer) | 4 bytes | -2,147,483,648 to 2,147,483,647
LongLong (LongLong integer) | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (Valid on 64-bit platforms only.)
LongPtr (Long integer on 32-bit systems, LongLong integer on 64-bit systems) | 4 bytes on 32-bit systems, 8 bytes on 64-bit systems | -2,147,483,648 to 2,147,483,647 on 32-bit systems, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 on 64-bit systems
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.79769313486231E308 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
Decimal | 14 bytes | +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/-0.0000000000000000000000000001
Date | 8 bytes | January 1, 100 to December 31, 9999
Object | 4 bytes | Any Object reference
String (variable-length) | 10 bytes + string length | 0 to approximately 2 billion
String (fixed-length) | Length of string | 1 to approximately 65,400
Variant (with numbers) | 16 bytes | Any numeric value up to the range of a Double
Variant (with characters) | 22 bytes + string length (24 bytes on 64-bit systems) | Same range as for variable-length String
User-defined (using Type) | Number required by elements | The range of each element is the same as the range of its data type.
Note Note

Arrays of any data type require 20 bytes of memory plus 4 bytes for each array dimension plus the number of bytes occupied by the data itself. The memory occupied by the data can be calculated by multiplying the number of data elements by the size of each element. For example, the data in a single-dimension array consisting of 4 Integer data elements of 2 bytes each occupies 8 bytes. The 8 bytes required for the data plus the 24 bytes of overhead brings the total memory requirement for the array to 32 bytes. On 64-bit platforms, SAFEARRAY's take up 24-bits (plus 4 bytes per Dim statement). The pvData member is an 8-byte pointer and it must be aligned on 8 byte boundaries.
Note Note

LongPtr is not a true data type because it transforms to a Long in 32-bit environments, or a LongLong in 64-bit environments. LongPtr should be used to represent pointer and handle values in Declare Statements and enables writing portable code that can run in both 32-bit and 64-bit environments.

A Variant containing an array requires 12 bytes more than the array alone.

Note Note

Use the StrConv function to convert one type of string data to another.


Boolean Data Type

 Copy code hover
[image]

Boolean Data Type
Send feedback

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

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


Byte Data Type

 Copy code hover
[image]

Byte Data Type
Send feedback

Byte variables are stored as single, unsigned, 8-bit (1-byte) numbers ranging in value from 0-255.

The Byte data type is useful for containing binary data.


Currency Data Type

 Copy code hover
[image]

Currency Data Type
Send feedback

Currency variables are stored as 64-bit (8-byte) numbers in an integer format, scaled by 10,000 to give a fixed-point number with 15 digits to the left of the decimal point and 4 digits to the right. This representation provides a range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807. The type-declaration character for Currency is the at sign (@).

The Currency data type is useful for calculations involving money and for fixed-point calculations in which accuracy is particularly important.


Date Data Type

 Copy code hover
[image]

Date Data Type
Send feedback

Date variables are stored as IEEE 64-bit (8-byte) floating-point numbers that represent dates ranging from 1 January 100 to 31 December 9999 and times from 0:00:00 to 23:59:59. Any recognizable literal date values can be assigned to Date variables. Date literals must be enclosed within number signs (#), for example, #January 1, 1993# or or #1 Jan 93# .

Date variables display dates according to the short date format recognized by your computer. Times display according to the time format (either 12-hour or 24-hour) recognized by your computer.

When other numeric types are converted to Date, values to the left of the decimal represent date information while values to the right of the decimal represent time. Midnight is 0 and midday is 0.5. Negative whole numbers represent dates before 30 December 1899.


Decimal Data Type

 Copy code hover
[image]

Decimal Data Type
Send feedback

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

Note Note

At this time the Decimal data type can only be used within a Variant, that is, you cannot declare a variable to be of type Decimal. You can, however, create a Variant whose subtype is Decimal using the CDec function.


Double Data Type

 Copy code hover
[image]

Double Data Type
Send feedback

Double (double-precision floating-point) variables are stored as IEEE 64-bit (8-byte) floating-point numbers ranging in value from -1.79769313486231E308 to -4.94065645841247E-324 for negative values and from 4.94065645841247E-324 to 1.79769313486232E308 for positive values. The type-declaration character for Double is the number sign (#).


Integer Data Type

 Copy code hover
[image]

Integer Data Type
Send feedback

Integer variables are stored as 16-bit (2-byte) numbers ranging in value from -32,768 to 32,767. The type-declaration character for Integer is the percent sign (%).

You can also use Integer variables to represent enumerated values. An enumerated value can contain a finite set of unique whole numbers, each of which has special meaning in the context in which it is used. Enumerated values provide a convenient way to select among a known number of choices, for example, black = 0, white = 1, and so on. It is good programming practice to define constants using the Const statement for each enumerated value.


Long Data Type

 Copy code hover
[image]

Long Data Type
Send feedback

Long (long integer) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647. The type-declaration character for Long is the ampersand (&).


LongLong Data Type

 Copy code hover
[image]

LongLong Data Type
Send feedback

LongLong (LongLong integer) variables are stored as signed 64-bit (8-byte) numbers ranging in value from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. The type-declaration character for LongLong is the caret (^). LongLong is a valid declared type only on 64-bit platforms.


LongPtr Data Type

 Copy code hover
[image]

LongPtr Data Type
Send feedback

LongPtr (Long integer on 32-bit systems, LongLong integer on 64-bit systems) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647 on 32-bit systems; and signed 64-bit (8-byte) numbers ranging in value from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 on 64-bit systems.

Note Note

LongPtr is not a true data type because it transforms to a Long in 32-bit environments, or a LongLong in 64-bit environments. Using LongPtr enables writing portable code that can run in both 32-bit and 64-bit environments. Use LongPtr for pointers and handles.


Object Data Type

 Copy code hover
[image]

Object Data Type
Send feedback

Object variables are stored as 32-bit (4-byte) addresses that refer to objects. Using the Set statement, a variable declared as an Object can have any object reference assigned to it.

Note Note

Although a variable declared with Object type is flexible enough to contain a reference to any object, binding to the object referenced by that variable is always late (run-time binding). To force early binding (compile-time binding), assign the object reference to a variable declared with a specific class name.


Single Data Type

 Copy code hover
[image]

Single Data Type
Send feedback

Single (single-precision floating-point) variables are stored as IEEE 32-bit (4-byte) floating-point numbers, ranging in value from -3.402823E38 to -1.401298E-45 for negative values and from 1.401298E-45 to 3.402823E38 for positive values. The type-declaration character for Single is the exclamation point (!).


String Data Type

 Copy code hover
[image]

String Data Type
Send feedback

There are two kinds of strings: variable-length and fixed-length strings.

  • A variable-length string can contain up to approximately 2 billion (2^31) characters.

  • A fixed-length string can contain 1 to approximately 64K (2^16) characters.

    Note Note

    A Public fixed-length string can't be used in a class module.

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


User-Defined Data Type

 Copy code hover
[image]

User-Defined Data Type
Send feedback

Any data type you define using the Type statement. User-defined data types can contain one or more elements of a data type, an array, or a previously defined user-defined type. For example:

Copy code Copy code
Type MyType
 MyName As String ' String variable stores a name.
 MyBirthDate As Date ' Date variable stores a birthdate.
 MySex As Integer ' Integer variable stores sex (0 for
End Type ' female, 1 for male).


Variant Data Type

 Copy code hover
[image]

Variant Data Type
Send feedback

The Variant data type is the data type for all variables that are not explicitly declared as some other type (using statements such as Dim, Private, Public, or Static). The Variant data type has no type-declaration character.

A Variant is a special data type that can contain any kind of data except fixed-length String data. (Variant types now support user-defined types.) A Variant can also contain the special values Empty, Error, Nothing, and Null. You can determine how the data in a Variant is treated using the VarType function or TypeName function.

Numeric data can be any integer or real number value ranging from -1.797693134862315E308 to -4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive values. Generally, numeric Variant data is maintained in its original data type within the Variant. For example, if you assign an Integer to a Variant, subsequent operations treat the Variant as an Integer. However, if an arithmetic operation is performed on a Variant containing a Byte, an Integer, a Long, or a Single, and the result exceeds the normal range for the original data type, the result is promoted within the Variant to the next larger data type. A Byte is promoted to an Integer, an Integer is promoted to a Long, and a Long and a Single are promoted to a Double. An error occurs when Variant variables containing Currency, Decimal, and Double values exceed their respective ranges.

You can use the Variant data type in place of any data type to work with data in a more flexible way. If the contents of a Variant variable are digits, they may be either the string representation of the digits or their actual value, depending on the context. For example:

Copy code Copy code
Dim MyVar As Variant
MyVar = 98052

In the preceding example, MyVar contains a numeric representation — 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 contains a numeric representation — 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 type, the result is an arithmetic sum.

The value Empty denotes a Variant variable that hasn't been initialized (assigned an initial value). A Variant containing Empty is 0 if it is used in a numeric context and a zero-length string ("") if it is used in a string context.

Don't confuse Empty with Null. Null indicates that the Variant variable intentionally contains no valid data.

In a Variant, Error is a special value used to indicate that an error condition has occurred in a procedure. However, unlike for other kinds of errors, normal application-level error handling does not occur. This allows you, or the application itself, to take some alternative action based on the error value. Error values are created by converting real numbers to error values using the CVErr function.


Directives

 Copy code hover
[image]

Directives
Send feedback

In this section

  • #Const Directive

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


#Const Directive

 Copy code hover
[image]

#Const Directive
Send feedback

Used to define conditional compiler constants for Visual Basic.

Syntax

#Const constname = expression

The #Const compiler directive syntax has these parts:

Part | Description
constname | Required; Variant (String). Name of the constant; follows standard variable naming conventions.
expression | Required. Literal, other conditional compiler constant, or any combination that includes any or all arithmetic or logical operators except Is.

Remarks

Conditional compiler constants are always Private to the module in which they appear. It is not possible to create Public compiler constants using the #Const directive. Public compiler constants can only be created in the user interface.

Only conditional compiler constants and literals can be used in expression. Using a standard constant defined with Const, or using a constant that is undefined, causes an error to occur. Conversely, constants defined using the #Const keyword can only be used for conditional compilation.

Conditional compiler constants are always evaluated at the module level, regardless of their placement in code.

Example

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

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


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

 Copy code hover
[image]

#If...Then...#Else Directive
Send feedback

Conditionally compiles selected blocks of Visual Basic code.

Syntax

#If expression Then

statements

[#ElseIf expression-n Then

[elseifstatements]]

[#Else

[elsestatements]]

#End If

The #If...Then...#Else directive syntax has these parts:

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

Remarks

The behavior of the #If...Then...#Else directive is the same as the If...Then...Else statement, except that there is no single-line form of the #If, #Else, #ElseIf, and #End If directives; that is, no other code can appear on the same line as any of the directives. Conditional compilation is typically used to compile the same program for different platforms. It is also used to prevent debugging code from appearing in an executable file. Code excluded during conditional compilation is completely omitted from the final executable file, so it has no size or performance effect.

Regardless of the outcome of any evaluation, all expressions are evaluated. Therefore, all constants used in expressions must be defined — any undefined constant evaluates as Empty.

Note Note

The Option Compare statement does not affect expressions in #If and #ElseIf statements. Expressions in a conditional-compiler directive are always evaluated with Option Compare Text.

Example

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

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


Error Messages

 Copy code hover
[image]

Error Messages
Send feedback

In this section

  • #Else clause must be preceded by a matching #If

  • #Else If, #Else, or #End If must be preceded by a matching #If

  • #ElseIf must be preceded by a matching #If or #ElseIf and followed by an #ElseIf, #Else, or #End If

  • <Item> is not a valid control type (Error 720)

  • A compatible ActiveX component must be a Visual Basic executable or a DLL

  • A form can't be moved or sized while minimized or maximized

  • A module is not a valid type

  • A procedure of that name already exists

  • A procedure with a ParamArray argument cannot be called with named arguments

  • A property or method call cannot include a reference to a private object, either as an argument or as a return value (Error 98)

  • ActiveX component can't create object or return reference to this object (Error 429)

  • ActiveX Component did not run correctly (Error 338)

  • ActiveX component not correctly registered (Error 336)

  • ActiveX control 'item' not found (Error 363)

  • Add-in can't reference project

  • Ambiguous name detected

  • Application-defined or object-defined error

  • Argument not optional (Error 449)

  • Argument required for Property Let or Property Set

  • Array already dimensioned

  • Array argument must be ByRef

  • Assignment to constant not permitted

  • Automation error (Error 440)

  • Automation object doesn't have a default value (Error 443)

  • Bad DLL calling convention (Error 49)

  • Bad file mode (Error 54)

  • Bad file name or number (Error 52)

  • Bad interface for Implements: interface contains data fields

  • Bad interface for Implements: interface is derived from another pure interface with non-restricted methods

  • Bad interface for Implements: interface is not derived from Iunknown

  • Bad interface for Implements: method does not return HRESULT

  • Bad interface for Implements: method has out-only or LCID parameter

  • Bad interface for Implements: method has parameter with too many levels of indirection

  • Bad interface for Implements: method has underscore in name

  • Bad interface for Implements: methods uses type that is not supported by Visual Basic

  • Bad record length (Error 59)

  • Bad record number (Error 63)

  • Beginning of search scope has been reached; do you want to continue from the end?

  • Block If without End If

  • Breakpoint not allowed on this line

  • ByRef argument type mismatch

  • Calling convention not supported by Visual Basic

  • Cannot define a KWID_tkPUBLIC user-defined type within a private object module

  • Cannot display specified name because it is hidden

  • Cannot handle events for the object specified

  • Cannot jump to specified type because it is in the specified library, which is not currently referenced

  • Can't add a reference to the specified file

  • Can't assign or coerce array of fixed-length string or user-defined type to Variant

  • Can't assign to an array

  • Can't call Friend procedure on an object that isn't an instance of the defining class (Error 97)

  • Can't change data types of array elements

  • Can't create AutoRedraw image (Error 480)

  • Can't create necessary temporary file (Error 322)

  • Can't display hidden procedure

  • Can't display system information

  • Can't edit module

  • Can't empty Clipboard (Error 520)

  • Can't enter break mode at this time

  • Can't execute code in break mode

  • Can't execute immediate statements in design mode

  • Can't exit design mode because control can't be created

  • Can't find DLL entry point in specified DLL

  • Can't find project or library

  • Can't find Windows Help .exe file

  • Can't Get or Put user-defined type containing object reference

  • Can't have paramarrays with optional arguments

  • Can't load module; invalid format

  • Can't load or unload this object (Error 361)

  • Can't make an assignment to a read-only property

  • Can't open Clipboard (Error 521)

  • Can't perform operation because the project is protected

  • Can't perform requested operation (Error 17)

  • Can't perform requested operation since the module is hidden

  • Can't place conditional breakpoint on an array

  • Can't print form image to this type of printer (Error 486)

  • Can't print minimized form image

  • Can't quit at this time

  • Can't record into running module

  • Can't ReDim, Erase, or assign to Variant that contains array whose element is With object

  • Can't remove control or reference; in use

  • Can't remove default reference

  • Can't rename with different drive (Error 74)

  • Can't save file to TEMP directory (Error 735)

  • Can't set the project name at this time

  • Can't show non-modal form when modal form is displayed

  • Can't sink this object's events because it's already firing events to the maximum number of supported event recipients (Error 96)

  • Can't start new recording until current session is ended

  • Can't use character device names in file names: 'item' (Error 320)

  • Case Else outside Select Case

  • Case without Select Case

  • Circular dependencies between modules

  • Class doesn't support Automation (Error 430)

  • Class is not set (Error 31018)

  • Class not registered on local machine (Error 463)

  • Class not registered. 'item 1'

  • Code execution has been interrupted

  • Code resource lock error (Error 455)

  • Code resource not found (Error 454)

  • Compile error in hidden module: <module name>

  • Component could not successfully create requested object

  • Component 'item' or one of its dependencies not correctly registered: a file is missing or invalid

  • Component not correctly registered

  • Component not found in registered location

  • Conflicting attributes were found in 'item'. The defaults will be used

  • Conflicting names were found in 'item1'. The name 'item2' will be used

  • Connection to type library or object library for remote process has been lost (Error 442)

  • Constant expression required

  • Constants, fixed-length strings, arrays, user-defined types, and Declare statements not allowed as Public members of an object module

  • Could not access system registry (Error 335)

  • Could not create reference: 'item'

  • Could not execute specified program

  • Could not start Internet Explorer

  • Current module does not support Print method

  • Cyclic reference of projects not allowed

  • Data value named not found (Error 327)

  • Definitions of property procedures for the same property are inconsistent

  • Deftype statements must precede declarations

  • Destination label too far away; loop, Select Case, or block If too large

  • Device I/O error (Error 57)

  • Device unavailable (Error 68)

  • Disk full (Error 61)

  • Disk not ready (Error 71)

  • Display more load errors?

  • Division by zero (Error 11)

  • Do without Loop

  • Do you want to export specified object before removing it?

  • Duplicate declaration in current scope

  • Duplicate definition

  • Duplicate Deftype statement

  • Duplicate Option statement

  • Duplicate procedure name

  • Duplicate resources with same type and name

  • Edit can't be undone--proceed anyway?

  • Else without If

  • Empty Enum type not allowed

  • Empty watch expression

  • End If without block If

  • End of search scope has been reached; do you want to continue from the beginning?

  • End Select without Select Case

  • End With without With

  • Enum types defined in standard modules or private classes cannot be used in public object modules as parameters or return types for public procedures, as public data members, or as fields of public user defined types

  • Error accessing the system registry

  • Error in loading DLL (Error 48)

  • Error loading from file (Error 31037)

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

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

  • Error saving to file (Error 31036)

  • Errors during load. Refer to 'item' for details

  • Errors occurred during load

  • Event handler is invalid

  • Event not found

  • Exit Do not within Do...Loop

  • Exit For not within For...Next

  • Exit Function not allowed in Sub or Property

  • Exit Property not allowed in Function or Sub

  • Exit Sub not allowed in Function or Property

  • Expected array

  • Expected End Function

  • Expected End Property

  • Expected End Sub

  • Expected End With

  • Expected Function or variable

  • Expected procedure, not module

  • Expected procedure, not project or library

  • Expected procedure, not user-defined type

  • Expected procedure, not variable

  • Expected Sub, Function, or Property

  • Expected user-defined type, not project

  • Expected variable or procedure, not Enum type

  • Expected variable or procedure, not module

  • Expected variable or procedure, not project

  • Expected: <various>

  • Expression too complex (Error 16)

  • External name not defined

  • Failed to activate control 'item 1'. This control may be incompatible with your application. Make sure you are using the version of the control that was provided with your application.

  • Failed to load control 'item1' from 'item2'. Your version of 'item2' may be outdated. Make sure you are using the version of the control that was provided with your application.

  • File already exists (Error 58)

  • File already open (Error 55)

  • File format no longer supported

  • File is read-only

  • File not found (Error 53)

  • File specified was not found

  • Filename or class name not found during Automation operation (Error 432)

  • Fixed or static data can't be larger than 64K

  • Fixed-length strings and use of the 'new' qualifier are not allowed for fields in a public user defined type defined in an object module

  • Fixed-length strings not allowed as the type of a public member of an object module; private object modules not allowed as the type of a public member of a public object module

  • For control variable already in use

  • For Each can only iterate over a collection object or an array

  • For Each control variable must be Variant or Object

  • For Each control variable on arrays must be Variant

  • For Each may not be used on array of user-defined type or fixed-length strings

  • For loop not initialized (Error 92)

  • For without Next

  • Form already displayed; can't show modally (Error 400)

  • Form not found (Error 424)

  • Forward reference to user-defined type

  • Function call on left-hand side of assignment must return Variant or Object

  • Function marked as restricted or uses a type not supported in Visual Basic

  • Identifier too long

  • Identifier under cursor isn't a procedure name

  • Illegal parameter. Can't write arrays (Error 328)

  • Illegal parameter. Can't write object because it does not support persistence.

  • Illegal parameter. Can't write user-defined type.

  • Incorrect DLL version

  • Incorrect OLE version

  • Input past end of file (Error 62)

  • Insufficient Immediate window memory to create variable

  • Insufficient memory to save Undo information

  • Insufficient project information to load project on platform or with version now being used

  • Interface not valid for Implements

  • Internal error (Error 51)

  • Invalid Access mode

  • Invalid attribute in Sub, Function, or Property

  • Invalid Base Address

  • Invalid character

  • Invalid Clipboard format (Error 460) [1 of 2]

  • Invalid Clipboard format (Error 460) [2 of 2]

  • Invalid data format

  • Invalid data type for constant

  • Invalid event name

  • Invalid file format (Error 321) [1 of 2]

  • Invalid file format (Error 321) [2 of 2]

  • Invalid format in resource file (Error 325)

  • Invalid in Immediate window

  • Invalid inside Enum

  • Invalid inside procedure

  • Invalid length for fixed-length string

  • Invalid Next control variable reference

  • Invalid object use (Error 425)

  • Invalid optional parameter type

  • Invalid or unqualified reference

  • Invalid ordinal (Error 452)

  • Invalid outside Enum

  • Invalid outside procedure

  • Invalid ParamArray use

  • Invalid pattern string (Error 93)

  • Invalid picture (Error 481) [1 of 2]

  • Invalid picture (Error 481) [2 of 2]

  • Invalid picture type (Error 485)

  • Invalid procedure call or argument (Error 5)

  • Invalid procedure name

  • Invalid property name

  • Invalid property value (Error 380) [1 of 2]

  • Invalid property value (Error 380) [2 of 2]

  • Invalid property-array index (Error 381)

  • Invalid qualifier

  • Invalid ReDim

  • Invalid syntax for conditional compiler constant declarations

  • Invalid Template

  • Invalid type-declaration character

  • Invalid use of AddressOf operator

  • Invalid use of base class name

  • Invalid use of Me keyword

  • Invalid use of New keyword

  • Invalid use of Null (Error 94)

  • Invalid use of object

  • Invalid watch expression

  • Item' already exists in project

  • 'item' cannot be added because it is referenced but not in use by any items in the project. To correct this, uncheck 'Remove information about unused ActiveX Controls' in Project Options.

  • Item' could not be loaded

  • 'Item' could not be loaded. Remove it from the list of available add-ins?

  • Item' could not be registered

  • 'item' designers can only be used in DLL projects

  • 'item' designers cannot be private

  • 'item' designers cannot be public in ActiveX EXE projects

  • 'item' designers must be public and cannot be used in Standard EXE projects

  • 'Item' has an old file format. When saved, it will be saved in a newer format.

  • 'item' has caused an access violation. Remove it from the list of available Add-Ins?

  • 'Item' is a binary form and can't be loaded into Visual Basic

  • 'Item' is a read-only file

  • 'item' is a single-threaded component and cannot be used in multi-threaded projects. Change the threading model for 'item' or contact the component vendor for an updated version.

  • 'Item' property can't be read at run time (Error 393)

  • 'Item' property can't be set at run time (Error 382)

  • 'Item' property is read-only (Error 383)

  • 'Item' property is write-only (Error 394)

  • 'Item' will not be loaded. Name is already in use

  • 'item1' is an invalid key. The file 'item2' can't be loaded

  • 'item1' is referenced by 'item2' project and cannot be updated.

  • Label not defined

  • Language/region setting has changed

  • License information for this component not found. You don't have an appropriate license to use this functionality in the design environment (Error 429)

  • Line isn't an executable statement

  • Line 'item1': All controls must precede menus; can't load control 'item2'.

  • Line 'item1': Can't create embedded object in 'item2'

  • Line 'item1': Can't create embedded object in 'item2'; license not found

  • Line 'item1': Can't load control 'item2'; containing control not a valid container.

  • Line 'item1': Can't load control 'item2'; license not found

  • Line 'item1': Can't load control 'item2'; name already in use.

  • Line 'item1': Can't set checked property in menu 'item2'. Parent menu can't be checked.

  • Line 'item1': Can't set Shortcut property in menu 'item2'. Parent menu cannot have a shortcut key.

  • Line 'item1': Class 'item2' of control 'item3' was not a loaded control class.

  • Line 'item1': Class name too long; truncated to 'item2'.

  • Line 'item1': Control name too long; truncated to 'item2'.

  • Line 'item1': Could not create reference: 'item2'

  • Line 'item1': Did not find an index property, and control 'item2' already exists.

  • Line 'item1': 'item2' has a quoted string where the property name should be.

  • Line 'item1': Maximum nesting level for controls exceeded with 'item2'.

  • Line 'item1': Missing or invalid control class in file 'item2 '.

  • Line 'item1': Missing or invalid control name in file 'item2'.

  • Line 'item1': Parent menu 'item2' can't be loaded as a separator.

  • Line 'item1': Property 'item2' in control 'item3' had an invalid property index.

  • Line 'item1': Property 'item2' in 'item3' could not be loaded.

  • Line 'item1': Property 'item2' in 'item3' could not be set.

  • Line 'item1': Property 'item2' in 'item3' had an invalid file reference.

  • Line 'item1': Property 'item2' in 'item3' had an invalid value.

  • Line 'item1': Property 'item2' in 'item3' must be a quoted string.

  • Line 'item1': Syntax error: property 'item2' in 'item3' was missing an equal sign (=).

  • Line 'item1': The CLSID 'item2' for 'item3' is invalid.

  • Line 'item1': The control name 'item2' is invalid.

  • Line 'item1': The file 'item2' could not be loaded.

  • Line 'item1': The Form or MDIForm name 'item2' is already in use; can't load this form.

  • Line 'item1': The Form or MDIForm name 'item2' is not valid; can't load this form.

  • Line 'item1': The property name 'item2' in 'item3' is invalid.

  • Line too long

  • Loop without Do

  • LSet allowed only on strings and user-defined types

  • LSet not allowed

  • Maximum number of watch expressions added

  • MDI forms are not allowed in multithreaded projects. Any MDI form will be removed from this project. To keep the MDI form in the project select Cancel and change threading model to Thread Pool with only 1 thread.

  • Member identifier already exists in object module from which this object module derives

  • Method not valid without suitable object

  • Method or data member not found (Error 461)

  • Missing end bracket

  • Module not found

  • Module too large

  • Must be first statement on the line

  • Must close or hide topmost modal form first (Error 402)

  • Must specify which item(s) to print

  • Name conflicts with existing module, project, or object library

  • Name 'item' conflicts with existing module, project, or object library

  • Named argument already specified

  • Named argument not found (Error 448)

  • Named arguments not allowed

  • Need property-array index (Error 385)

  • Next without For

  • No creatable public component detected. Press F1 for more information.

  • No Help available

  • No object (Error 31004)

  • No text selected

  • No watch expression selected

  • Not a legal object name: 'item

  • Not enough memory to completely save project

  • Not enough memory to load file

  • Not enough memory to run; quitting

  • Object already loaded (Error 360)

  • Object does not have a Property Let procedure

  • Object does not source Automation events

  • Object doesn't support current locale setting (Error 447)

  • Object doesn't support named arguments (Error 446)

  • Object doesn't support this action (Error 445)

  • Object doesn't support this property or method (Error 438)

  • Object library feature not supported

  • Object library for Visual Basic for Applications not found

  • Object library invalid or contains references to object definitions that could not be found

  • Object library not registered

  • Object library's language setting incompatible with current project

  • Object module must implement all procedures in interface

  • Object required (Error 424)

  • Object server not found (Error 337)

  • Object variable not set (Error 91)

  • Object was unloaded (Error 364)

  • One or more files in the project have changed. Do you want to save the changes now?

  • One or more instances of this object are running. Can't remove it at this time.

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

  • Only comments may appear after End Sub, End Function, or End Property

  • Only public user defined types defined in public object modules can be used as parameters or return types for public procedures of class modules or as fields of public user defined types

  • Only valid in object module

  • Operation not allowed in DLL

  • Option Private Module not permitted in object module

  • Optional argument must be Variant

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

  • Out of memory (Error 31001)

  • Out of memory (Error 7)

  • Out of memory; some watches might have been deleted

  • Out of resources

  • Out of stack space (Error 28)

  • Out of string space (Error 14)

  • Overflow (Error 6)

  • ParamArray must be declared as an array of Variant

  • Path not found (Error 76)

  • Path/File access error (Error 75)

  • Permission denied (Error 70)

  • Permission to use object denied (Error 419)

  • Please see the Readme file for more information on this error

  • Printer driver does not support specified property (Error 483)

  • Printer error (Error 482) [1 of 2]

  • Printer error (Error 482) [2 of 2]

  • Private Enum and user-defined types cannot be used as parameters or return types for public procedures, public data members, or fields of public user-defined types

  • Private object modules cannot be used in public object modules as parameters or return types for public procedures, as public data members, or as fields of public user defined types

  • Problem getting printer information from the system; make sure the printer is set up correctly. (Error 484)

  • Procedure declaration does not match description of event or procedure having same name

  • Procedure too large

  • Procedure type mismatch

  • Programmatic ID string too long 'item'. The Programmatic ID must be 39 characters or less.

  • Project <name> has been modified. Do you wish to save the changes now?

  • Project contains too many procedure, variable, and constant names

  • Project file is read-only

  • Project is unviewable.

  • Project not found

  • Property Get can't be executed at run time (Error 393)

  • Property Get can't be executed on write-only property (Error 394)

  • Property let procedure not defined and property get procedure did not return an object (Error 451)

  • Property not found (Error 422)

  • Property or method not found (Error 423)

  • Property Set can't be executed at run time (Error 382)

  • Property Set can't be used with a read-only property (Error 383)

  • Property Set not permitted (Error 387)

  • Qualified name disallowed in module scope

  • Qualifier must be collection

  • Range has no values

  • Replacements too long (Error 746)

  • Requested type library or wizard is not a VBA project

  • Resume without error (Error 20)

  • Return without GoSub (Error 3)

  • RSet allowed only on strings

  • Run-time error <number>:

  • Search string must be specified

  • Search string must be specified (VBE)

  • Search string too long or complex

  • Search text isn't found

  • Search text not found (Error 744)

  • Seek failed: can't read/write from the disk

  • Select Case without End Select

  • Selected watch expression invalid

  • Set Next Statement can only apply to executable lines within current procedure.

  • SHARE.EXE required

  • Specified ActiveX component not correctly registered or not found

  • Specified DLL function not found (Error 453)

  • Specified format doesn't match format of data (Error 461)

  • Specified library or project already referenced

  • Statement invalid inside Type block

  • Statement invalid outside Type block

  • Statement too complex

  • Statements or labels invalid between Select Case and first Case

  • String value too long to process; form load aborted

  • Sub, Function, or Property not defined (Error 35)

  • Subscript out of range (Error 9)

  • Syntax error

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

  • System error 'item'

  • The .VBP file for this project contains an invalid or corrupt library references ID

  • The ActiveX Designer's Type Information does not match what was saved. Unable to Load.

  • The application description can't be more than 2000 characters long

  • The binary compatibility DLL or EXE contains a parameter type or return type whose definition cannot be found

  • The binary compatibility DLL or EXE contains an Implements type whose definition cannot be found

  • The code in this project must be updated for use on 64-bit systems

  • The current project does not support files of this type

  • The edit may make the object module incompatible with the previously specified compatible ActiveX component

  • The file 'item' is marked as a version not supported by the current version of Visual Basic and won't be loaded

  • The file 'item' is out of date. This program requires a later version (Error 368)

  • The file 'item' was not registerable as an ActiveX Component.

  • The form class contained in the specified file is not supported in Visual Basic for Applications; the file can't be loaded.

  • The library containing this symbol is not referenced by the current project, so the symbol is undefined. Would you like to add a reference to the containing library now?

  • The load behavior for 'item' could not be updated because of current registry permissions.

  • The project file 'item' is corrupt and can't be loaded

  • The project file 'item1' contains invalid 'item2' key value

  • The project file 'item1' contains invalid 'item2' key value. Valid range is 0 to 'item3'

  • The project file 'item1' contains invalid key 'item2'.

  • The project file 'item1' contains invalid key 'item2'. The project can't be loaded

  • The project name is too long. Name has been truncated

  • The remote server machine does not exist or is unavailable (Error 462)

  • The selected Add-In has not been confirmed to be 'Command Line Safe,' and may require some user intervention (possible UI)

  • The specified file could not be loaded.

  • The specified object can't be used as an owner form for Show() (Error 371)

  • The specified region has been searched

  • The specified region has been searched and 1 replacement was made

  • The specified region has been searched and the replacements were made

  • Translation failed. Please check the trnslate.log file for more information.

  • This action will reset your project, proceed anyway?

  • This array is fixed or temporarily locked (Error 10)

  • This command will stop the debugger.

  • This component doesn't raise any events

  • This component doesn't support this set of events (Error 459)

  • This control can only be used with 'item' designers

  • This control cannot be used with 'item' designers

  • This designer cannot be used because it uses features that are not supported in this version of Visual Basic

  • This document was opened with Macros Disabled

  • This edit requires a Reset

  • This feature requires Internet Explorer 'item' or greater. You can obtain the latest version from www.microsoft.com

  • This interaction between compiled and design environment components is not supported

  • This key is already associated with an element of this collection (Error 457)

  • This project is currently referenced by another project and cannot be closed

  • This VBA project was created while running VBA in a different application. You may only open it from inside the same application in which it was created.

  • Too many arguments

  • Too many dimensions

  • Too many DLL application clients

  • Too many files (Error 67)

  • Too many line continuations

  • Too many local, nonstatic variables

  • Too many module-level variables

  • Trappable Errors

  • Type mismatch (Error 13)

  • Type mismatch: array or user-defined type expected

  • Type not supported in Visual Basic

  • Type-declaration character does not match declared data type

  • Type-declaration character not allowed

  • Type-declaration character required

  • Unable to activate object (Error 31027)

  • Unable to create embedded object (Error 31032)

  • Unable to display Help

  • Unable to read from the disk

  • Unable to unload within this context (Error 365)

  • Unable to write Designer cache file 'item'; will just use regular files on Load

  • Unable to write to the disk

  • Unexpected compile error

  • Unexpected error

  • Unexpected error occurred in code generator or linker

  • Unexpected error; please contact Microsoft Technical Support

  • Unexpected error; quitting

  • Unmatched brackets in search string

  • Unrecognized project language

  • User interrupt occurred (Error 18)

  • User-defined type may not be passed ByVal

  • User-defined type not defined

  • User-defined type without members not allowed

  • Valid values are whole numbers from 1 to 32

  • Valid values are whole numbers from 2 to 60

  • Variable not defined

  • Variable not yet created in this context

  • Variable required. Can't assign to this expression

  • Variable uses a type not supported in Visual Basic (Error 458)

  • Version number missing or invalid; Visual Basic 5.0 assumed

  • Version numbers must be in the range 0 to 9999

  • Visual Basic can't load 'item' because it is not in the system registry. Please ensure that all add-ins have been installed correctly.

  • Warning: custom language settings not portable

  • Wend without While

  • While without Wend

  • Windowless controls can't have menus.

  • With object must be user-defined type, Object, or Variant

  • Wizards can't reference projects

  • Wrong number of arguments (Error 450)

  • Wrong number of dimensions

  • Wrong version of operating system; requires Windows NT 3.51 (build 'item1' or later) or Windows 95 (build 'item2' or later)

  • You must save a project before you can reference it.

  • You must terminate the #If block with an #End If


#Else clause must be preceded by a matching #If

 Copy code hover
[image]

#Else clause must be preceded by a matching #If
Send feedback

#Else is a conditional compilation directive. This error has the following cause and solution:

  • An #Else clause was detected that isn't preceded by a matching #If or #ElseIf. Check to see if a preceding #If has been separated from this #Else by an #End If. Note that only one #Else is permitted in each #If block, so two successive #Else clauses cause this error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


#Else If, #Else, or #End If must be preceded by a matching #If

 Copy code hover
[image]

#Else If, #Else, or #End If must be preceded by a matching #If
Send feedback

#Else If, #Else, and #End If are conditional compilation directives. This error has the following cause and solution:

  • An #Else If, #Else, or #End If was detected that isn't preceded by a matching #If clause. Check to see if the intended #If has been separated from the clause in question by an intervening block or if the intended #If is preceded by a number sign (#) sign. If everything else is in order, place an #If clause in the appropriate position.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


#ElseIf must be preceded by a matching #If or #ElseIf and followed by an #ElseIf, #Else, or #End If

 Copy code hover
[image]

#ElseIf must be preceded by a matching #If or #ElseIf and followed by an #ElseIf, #Else, or #End If
Send feedback

#ElseIf is a conditional compilation directive. This error has the following causes and solutions:

  • An #ElseIf has been detected that isn't preceded by an #If or #ElseIf. Place an #If statement before the #ElseIf or remove an incorrectly placed preceding #End If.

  • An #ElseIf has been detected that is preceded by an #Else or #End If. Appropriately terminate the preceding #If block, or change the preceding #Else to an #ElseIf.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


 Copy code hover
[image]

<Item> is not a valid control type (Error 720)
Send feedback

Only valid ActiveX components can be assigned as controls on forms. This error has the following cause and solution:

  • You attempted to assign an ActiveX component as a control on a form that isn't recognized as a valid control component. See the Help topics for building ActiveX controls to determine what constitutes an acceptable control.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


A compatible ActiveX component must be a Visual Basic executable or a DLL

 Copy code hover
[image]

A compatible ActiveX component must be a Visual Basic executable or a DLL
Send feedback

A compatible ActiveX component is one that you specify as a compatible ActiveX component. This error has the following cause and solution:

  • Visual Basic tried to access an object you specified as a compatible ActiveX component, but the file specified wasn't an executable file or dynamic-link library (DLL) created by Visual Basic.

    Only .exe files and DLLs created by Visual Basic are valid entries in the Compatible ActiveX Component field of the Project Properties dialog box accessed through the Project menu. If possible, load the project into Visual Basic and choose the Make Project.exe File command from the File menu to create a Visual Basic executable file. If the file is already an executable file that wasn't created by Visual Basic, or if the file can't be loaded into Visual Basic, consult the documentation of the file to find out if it can be converted to a Visual Basic executable file or if the vendor can supply an executable file created by Visual Basic.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


A form can't be moved or sized while minimized or maximized

 Copy code hover
[image]

A form can't be moved or sized while minimized or maximized
Send feedback

This error has the following causes and solutions:

  • You've attempted to move or size a form while it's minimized or maximized, and this is not allowed.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


A module is not a valid type

 Copy code hover
[image]

A module is not a valid type
Send feedback

A standard module doesn't represent a class and can't be instantiated in the form of a variable. This error has the following cause and solution:

  • You used the name of a standard module in a Dim or Set declaration. Check the spelling of the module name and make sure it corresponds to a form, MDI form, or class module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


A procedure of that name already exists

 Copy code hover
[image]

A procedure of that name already exists
Send feedback

Procedure names within the same scope must be unique. Change the name of the procedure.


A procedure with a ParamArray argument cannot be called with named arguments

 Copy code hover
[image]

A procedure with a ParamArray argument cannot be called with named arguments
Send feedback

All arguments in a call to a procedure defined with a ParamArray must be positional. This error has the following cause and solution:

  • Named-argument syntax appears in a procedure call.

    The named-argument calling syntax can't be used to call a procedure that includes a ParamArray parameter. To supply only some elements of the ParamArray, use commas as placeholders for those elements you want to omit. For example, in the following call, if the ParamArray arguments begin after Arg2, values are being passed only for the first, third, and sixth values in the ParamArray:

    Copy code Copy code
    MySub Arg1, Arg2, 7,, 44,,,3
    Note Note

    The ParamArray always represents the last items in the argument list.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


A property or method call cannot include a reference to a private object, either as an argument or as a return value (Error 98)

 Copy code hover
[image]

A property or method call cannot include a reference to a private object, either as an argument or as a return value (Error 98)
Send feedback

Private objects should never be passed outside a project. The following, all of which are prohibited, are possible causes for the error:

  • A client invoked a property or method of an out-of-process component and attempted to pass a reference to a private object as one of the arguments. A client invoked a property or method of an out-of-process component and the component attempted to return a reference to a private object, or to assign such a reference to a ByRef argument.

  • An out-of-process component has invoked a call-back method on its client and attempted to pass a reference to a private object.

  • An out-of-process component attempted to pass a reference to a private object as an argument of an event it was raising.

  • A client attempted to assign a private object reference to a ByRef argument of an event it was handling.

Note that although Visual Basic prevents you from passing references to nonvisual private objects across processes, there are some cases in which Visual Basic can't detect this error and thus can't prevent it. Private objects are not designed to be used outside your project. If you pass them to a client, you may jeopardize program stability and cause incompatibility with future versions of Visual Basic. If you need to pass a private class of your own to a client, set the Instancing property to a value other than Private.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


ActiveX component can't create object or return reference to this object (Error 429)

 Copy code hover
[image]

ActiveX component can't create object or return reference to this object (Error 429)
Send feedback

Creating objects requires that the object's class be registered in the system registry and that any associated dynamic-link libraries (DLL) be available. This error has the following causes and solutions:

  • The class isn't registered. For example, the system registry has no mention of the class, or the class is mentioned, but specifies either a file of the wrong type or a file that can't be found. If possible, try to start the object's application. If the registry information is out of date or wrong, the application should check the registry and correct the information. If starting the application doesn't fix the problem, rerun the application's setup program.

  • A DLL required by the object can't be used, either because it can't be found, or it was found but was corrupted. Make sure all associated DLLs are available. For example, the Data Access Object (DAO) requires supporting DLLs that vary among platforms. You may have to rerun the setup program for such an object if that is what is causing this error.

  • The object is available on the machine, but it is a licensed Automation object, and can't verify the availability of the license necessary to instantiate it.

    Some objects can be instantiated only after the component finds a license key, which verifies that the object is registered for instantiation on the current machine. When a reference is made to an object through a properly installed type library or object library, the correct key is supplied automatically.

    If the attempt to instantiate is the result of a CreateObject or GetObject call, the object must find the key. In this case, it may search the system registry or look for a special file that it creates when it is installed, for example, one with the extension .lic. If the key can't be found, the object can't be instantiated. If an end user has improperly set up the object's application, inadvertently deleted a necessary file, or changed the system registry, the object may not be able to find its key. If the key can't be found, the object can't be instantiated. In this case, the instantiation may work on the developer's system, but not on the user's system. It may be necessary for the user to reinstall the licensed object.

  • You are trying to use the GetObject function to retrieve a reference to class created with Visual Basic. GetObject can't be used to obtain a reference to a class created with Visual Basic.

  • Access to the object has explicitly been denied. For example, you may be trying to access a data object that's currently being used and is locked to prevent deadlock situations. If that's the case, you may be able to access the object at another time.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


ActiveX Component did not run correctly (Error 338)

 Copy code hover
[image]

ActiveX Component did not run correctly (Error 338)
Send feedback

The ActiveX component's .exe file failed to run correctly. There may be a problem with the information in the registry.


ActiveX component not correctly registered (Error 336)

 Copy code hover
[image]

ActiveX component not correctly registered (Error 336)
Send feedback

The ActiveX component has not been properly registered in the system registry.


ActiveX control 'item' not found (Error 363)

 Copy code hover
[image]

ActiveX control 'item' not found (Error 363)
Send feedback

The form being loaded contains an ActiveX control that isn't part of the current project. This error has the following causes and solutions:

  • You may have manually edited the project's .vbp file to add a form containing an ActiveX control that isn't already part of the project. After the project loads, use the Add File command on the File menu to add the ActiveX control to the project.

  • You may have manually edited the project's .vbp file to add a form containing an earlier version of an ActiveX control than the ActiveX control that is already part of the project. After the project loads, delete the earlier version from the form and put the later version of the control on the form.


Add-in can't reference project

 Copy code hover
[image]

Add-in can't reference project
Send feedback

Projects are dynamic, but add-ins are static. This error has the following cause and solution:

  • You tried to create an add-in from a project that references another project.

    The semantics of projects can change in a way that affects referencing projects and add-ins. Therefore, you can't create an add-in from a project that references projects.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Ambiguous name detected

 Copy code hover
[image]

Ambiguous name detected
Send feedback

The identifier conflicts with another identifier or requires qualification. This error has the following causes and solutions:

  • More than one object in the same scope may have elements with the same name.

    Qualify the element name by including the object name and a period. For example:

    object.property

    Module-level identifiers and project-level identifiers (module names and referenced project names) may be reused in a procedure, although it makes programs harder to maintain and debug. However, if you want to refer to both items in the same procedure, the item having wider scope must be qualified. For example, if MyID is declared at the module level of MyModule , and then a procedure-level variable is declared with the same name in the module, references to the module-level variable must be appropriately qualified:

    Copy code Copy code
    Dim MyID As String
Sub MySub
MyModule.MyID = "This is module-level variable"
Dim MyID As String
MyID = "This is the procedure-level variable"
Debug.Print MyID
Debug.Print MyModule.MyID
End Sub

  • An identifier declared at module-level conflicts with a procedure name. For example, this error occurs if the variable MyID is declared at module level, and then a procedure is defined with the same name:

    Copy code Copy code
    Public MyID
Sub MyID
. . .
End Sub

    In this case, you must change one of the names because qualification with a common module name would not resolve the ambiguity. Procedure names are Public by default, but variable names are Private unless specified as Public.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Application-defined or object-defined error

 Copy code hover
[image]

Application-defined or object-defined error
Send feedback

This message is displayed when an error generated with the Raise method or Error statement doesn't correspond to an error defined by Visual Basic for Applications. It is also returned by the Error function for arguments that don't correspond to errors defined by Visual Basic for Applications. Thus it may be an error you defined, or one that is defined by an object, including host applications like Microsoft Excel, Visual Basic, and so on. For example, Visual Basic forms generate form-related errors that can't be generated from code simply by specifying a number as an argument to the Raise method or Error statement. This message has the following causes and solutions:

  • Your application executed an Err.Raise n or Error n statement, but the number n isn't defined by Visual Basic for Applications. If this was what was intended, you must use Err.Raise and specify additional arguments so that an end user can understand the nature of the error. For example, you can include a description string, source, and help information. To regenerate an error that you trapped, this approach will work if you don't execute Err.Clear before regenerating the error. If you execute Err.Clear first, you must fill in the additional arguments to the Raise method. Look at the context in which the error occurred, and make sure you are regenerating the same error.

  • It may be that in accessing objects from other applications, an error was propagated back to your program that can't be mapped to a Visual Basic error.

    Copy code Copy code
    For index = 1 to 500
Debug.Print Error$(index)
Next index

    Check the documentation for any objects you have accessed. The Err object's Source property should contain the programmatic ID of the application or object that generated the error. To understand the context of an error returned by an object, you may want to use the On Error Resume Next construct in code that accesses objects, rather than the On Error GoTo line syntax.

    Note Note

    In the past, programmers often used a loop to print out a list of all trappable error message strings. Typically this was done with code such as the following:
    Copy code Copy code
    For index = 1 to 500
Debug.Print Error$(index)
Next index
    Note Note

    Such code still lists all the Visual Basic for Applications error messages, but displays "Application-defined or object-defined error" for host-defined errors, for example those in Visual Basic that relate to forms, controls, and so on. Many of these are trappable run-time errors. You can use the Help Search dialog box to find the list of trappable errors specific to your host application. Click Search, type Trappable in the first text box, and then click Show Topics. Select Trappable Errors in the lower list box and click Go To.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Argument not optional (Error 449)

 Copy code hover
[image]

Argument not optional (Error 449)
Send feedback

The number and types of arguments must match those expected. This error has the following causes and solutions:

  • Incorrect number of arguments. Supply all necessary arguments. For example, the Left function requires two arguments; the first representing the character string being operated on, and the second representing the number of characters to return from the left side of the string. Because neither argument is optional, both must be supplied.

  • Omitted argument isn't optional. An argument can only be omitted from a call to a user-defined procedure if it was declared Optional in the procedure declaration. Either supply the argument in the call or declare the parameter Optional in the definition.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Argument required for Property Let or Property Set

 Copy code hover
[image]

Argument required for Property Let or Property Set
Send feedback

The purpose of Property Let and Property Set procedures is to give a new value to a property. This error has the following causes and solutions:

  • In setting the property, the value doesn't appear in the right place. Place the value to which you want to set the property on the right side of the expression setting the property value.

  • In the procedure definition, the parameter defined to receive the value passed on the right side of the expression is missing or misplaced.

    Specify a parameter for the value argument list in the procedure definition. If the procedure takes more than one argument, the property-value parameter must appear last in the list.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Array already dimensioned

 Copy code hover
[image]

Array already dimensioned
Send feedback

A static array can only be dimensioned once. This error has the following causes and solutions:

  • You attempted to change the dimensions of a static array with a ReDim statement; only dynamic arrays can be redimensioned. Either remove the redimensioning or use a dynamic array. To define a dynamic array, use a Dim, Public, Private, or Static statement with empty parentheses. For example: Dim MyArray() In a procedure, you can define a dynamic array with the ReDim or Static statement using a variable for the number of elements:

    Copy code Copy code
    Dim MyArray()
    Copy code Copy code
    ReDim MyArray(n)

    In a procedure, you can define a dynamic array with the ReDim or Static statement using a variable for the number of elements: ReDim MyArray(n)

  • An Option Base statement occurs after array dimensions are set. Make sure any Option Base statement precedes all array declarations.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Array argument must be ByRef

 Copy code hover
[image]

Array argument must be ByRef
Send feedback

Arrays declared with Dim, ReDim, or Static can't be passed ByVal. This error has the following cause and solution:

  • You tried to pass a whole array ByVal. An individual element of an array can be passed ByVal (by value), but a whole array must be passed ByRef (by reference). Note that ByRef is the default. If you must pass an array ByVal to prevent changes to the array's elements from being propagated back to the caller, you can pass the array argument in its own set of parentheses, or you can place it into a Variant, and then pass the Variant to the ByVal parameter, as follows:

    Copy code Copy code
    Dim MyVar As Variant
MyVar = OldArray()

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Assignment to constant not permitted

 Copy code hover
[image]

Assignment to constant not permitted
Send feedback

A constant represents a read-only value. This error has the following causes and solutions:

  • You tried to assign a new value to a variable declared with Const, or to a type library constant. If you need to assign a new value, declare an ordinary variable of the type desired and assign your value to that variable. If you need a variable with a restricted set of values, you can declare an enumeration, using the Enum statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Automation error (Error 440)

 Copy code hover
[image]

Automation error (Error 440)
Send feedback

When you access Automation objects, specific types of errors can occur. This error has the following possible causes and solutions:

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

    Check the properties of the Err object to determine the source and nature of the error. Also try using the On Error Resume Next statement immediately before the accessing statement, and then check for errors immediately following the accessing statement.

  • The Office add-in that you are trying to use has been disabled by your System Administrator.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Automation object doesn't have a default value (Error 443)

 Copy code hover
[image]

Automation object doesn't have a default value (Error 443)
Send feedback

When you specify an object name without a property or method, Visual Basic assumes you are referencing the object's default member (property or method). However, not all objects expose a default member. This error has the following cause and solution:

  • Visual Basic can't determine the default member for the specified object. Check the object's documentation and give an explicit specification for the property or method.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad DLL calling convention (Error 49)

 Copy code hover
[image]

Bad DLL calling convention (Error 49)
Send feedback

Arguments passed to a dynamic-link library (DLL) or Macintosh code resource routine must exactly match those expected by the routine. Calling conventions deal with number, type, and order of arguments. This error has the following causes and solutions:

  • Your program is calling a routine in a DLL (in Windows) or a code resource (on the Macintosh) that's being passed the wrong type of arguments. Make sure all argument types agree with those specified in the declaration of the routine you are calling.

  • Your program is calling a routine in a DLL (in Windows) or a code resource (on the Macintosh) that's being passed the wrong number of arguments. Make sure you are passing the same number of arguments indicated in the declaration of the routine you are calling.

  • Your program is calling a routine in a DLL, but isn't using the StdCall calling convention. If the DLL routine expects arguments by value, then make sure ByVal is specified for those arguments in the declaration for the routine.

  • Your Declare statement for a Windows DLL includes CDecl. The CDecl keyword applies only to the Macintosh.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad file mode (Error 54)

 Copy code hover
[image]

Bad file mode (Error 54)
Send feedback

Statements used in manipulating file contents must be appropriate to the mode in which the file was opened. This error has the following causes and solutions:

  • A Put or Get statement is specifying a sequential file. Put and Get can only refer to files opened for Random or Binary access.

  • A Print # statement specifies a file opened for an access mode other than Output or Append. Use a different statement to place data in the file or reopen the file in an appropriate mode.

  • An Input # statement specifies a file opened for an access mode other than Input. Use a different statement to place data in the file or reopen the file in Input mode.

  • You attempted to write to a read-only file. Change the read/write status of the file or don't try to write to it.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad file name or number (Error 52)

 Copy code hover
[image]

Bad file name or number (Error 52)
Send feedback

An error occurred trying to access the specified file. This error has the following causes and solutions:

  • A statement refers to a file with a file number or file name that is:

    • Not specified in the Open statement or was specified in an Open statement, but has since been closed. Specify the file name in an Open statement. Note that if you invoked the Close statement without arguments, you may have inadvertently closed all currently open files, invalidating all file numbers.

    • Out of the range of file numbers (1 - 511). If your code is generating file numbers algorithmically, make sure the numbers are valid.

  • There is an invalid name or number.

    Copy code Copy code
    LETTER.DOC
My Memo.Txt
BUDGET.92
12345678.901
Second Try.Rpt

    File names must conform to operating system conventions as well as Basic file-naming conventions. In Microsoft Windows, use the following conventions for naming files and directories:

    • The name of a file or directory can have two parts: a name and an optional extension. The two parts are separated by a period, for example, myfile.new.

    • The name can contain up to 255 characters.

    • The name must start with either a letter or number. It can contain any uppercase or lowercase characters (file names aren't case-sensitive) except the following characters: quotation mark ("), apostrophe ('), slash (/), backslash (\), colon (:), and vertical bar (|).

    • The name can contain spaces.

    • The following names are reserved and can't be used for files or directories: CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, and NUL. For example, if you try to name a file PRN in an Open statement, the default printer will simply become the destination for Print # and Write # statements directed to the file number specified in the Open statement.

    • The following are examples of valid Microsoft Windows file names:

    • On the Macintosh, a file name can include any character except the colon (:), and can contain spaces. Null characters (Chr(0)) aren't allowed in any file names.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad interface for Implements: interface contains data fields

 Copy code hover
[image]

Bad interface for Implements: interface contains data fields
Send feedback

This error has the following cause and solution:

  • The interface or class contains data fields.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad interface for Implements: interface is derived from another pure interface with non-restricted methods

 Copy code hover
[image]

Bad interface for Implements: interface is derived from another pure interface with non-restricted methods
Send feedback

This error has the following cause and solution:

  • The interface is directly or indirectly derived from a pure interface that contains non-restricted methods.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad interface for Implements: interface is not derived from Iunknown

 Copy code hover
[image]

Bad interface for Implements: interface is not derived from Iunknown
Send feedback

The Implements statement is used to specify an interface or class that will be implemented in the class module in which it appears. This error has the following cause and solution:

  • The interface or class contains a method that uses data types that aren't supported by Basic.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad interface for Implements: method does not return HRESULT

 Copy code hover
[image]

Bad interface for Implements: method does not return HRESULT
Send feedback

The Implements statement is used to specify an interface or class that will be implemented in the class module in which it appears. This error has the following cause and solution:

  • The interface or class contains a method name that returns a value that isn't of type HRESULT.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad interface for Implements: method has out-only or LCID parameter

 Copy code hover
[image]

Bad interface for Implements: method has out-only or LCID parameter
Send feedback

The Implements statement is used to specify an interface or class that will be implemented in the class module in which it appears. This error has the following cause and solution:

  • The interface or class contains a method that has a parameter that is of type out-only or LCID.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad interface for Implements: method has parameter with too many levels of indirection

 Copy code hover
[image]

Bad interface for Implements: method has parameter with too many levels of indirection
Send feedback

The Implements statement is used to specify an interface or class that will be implemented in the class module in which it appears. This error has the following cause and solution:

  • The interface or class contains a method that has a parameter with too many levels of indirection. For example, usage of double indirections of integer or triple indirection of user-defined types.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad interface for Implements: method has underscore in name

 Copy code hover
[image]

Bad interface for Implements: method has underscore in name
Send feedback

The Implements statement is used to specify an interface or class that will be implemented in the class module in which it appears. This error has the following cause and solution:

  • The interface or class contains a method name that contains an underscore character.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad interface for Implements: methods uses type that is not supported by Visual Basic

 Copy code hover
[image]

Bad interface for Implements: methods uses type that is not supported by Visual Basic
Send feedback

The Implements statement is used to specify an interface or class that will be implemented in the class module in which it appears. This error has the following cause and solution:

  • The interface or class contains a method that aren't supported by Basic.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad record length (Error 59)

 Copy code hover
[image]

Bad record length (Error 59)
Send feedback

The length of a record variable in a Get or Put statement must be the length specified in its corresponding Open statement. This error has the following causes and solutions:

  • The record variable's length differs from the length specified in the corresponding Open statement. Make sure the sum of the sizes of fixed-length variables in the user-defined type defining the record variable's type is the same as the value stated in the Open statement's Len clause. In the following example, assume RecVar is a variable of the appropriate type. You can use the Len function to specify the length, as follows:

    Copy code Copy code
    Open MyFile As #1 Len = Len(RecVar)

  • The variable in a Put statement is (or includes) a variable-length string. Because a 2-byte descriptor is always added to a variable-length string placed in a random access file with Put, the variable-length string must be at least 2 characters shorter than the record length specified in the Len clause of the Open statement.

  • The variable in a Put statement is (or includes) a Variant. Like variable-length strings, Variant data types also require a 2-byte descriptor. Variants containing variable-length strings require a 4-byte descriptor. Therefore, for variable-length strings in a Variant, the string must be at least 4 bytes shorter than the record length specified in the Len clause.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad record number (Error 63)

 Copy code hover
[image]

Bad record number (Error 63)
Send feedback

An error occurred during the attempted file access. This error has the following cause and solution:

  • The record number in a Put or Get statement is less than or equal to zero. Check the calculations used in generating the record number. Make sure that the variables containing the record number or used in calculating record numbers are spelled correctly. A misspelled variable name is implicitly declared and initialized to zero, unless you have properly placed Option Explicit in the module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Beginning of search scope has been reached; do you want to continue from the end?

 Copy code hover
[image]

Beginning of search scope has been reached; do you want to continue from the end?
Send feedback

Your search was unsuccessful. This condition has the following cause and solution:

  • Your upward search has reached the beginning of the specified scope. You can continue searching from the end of the search scope, or cancel and change the scope of the search.


Block If without End If

 Copy code hover
[image]

Block If without End If
Send feedback

An error occurred due to an incomplete statement. This error has the following cause and solution:

  • An If statement is used without a corresponding End If statement. A multiline If statement must terminate with a matching End If statement. For nested If...End If statements, make sure there is a correctly matched If...End If structure inside each enclosing If...End If structure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Breakpoint not allowed on this line

 Copy code hover
[image]

Breakpoint not allowed on this line
Send feedback

Breakpoints can only be placed on certain parts of statements. This error has the following causes:

  • You tried to place a breakpoint on a line that can't accept a breakpoint, for example:

    • A line that contains only comments.

    • A line that contains only line labels.

    • A line that contains only declarations (Const, Dim, Static, Type, and so on).

    • Any line in a hidden module.

    • Any line in the Immediate window.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


ByRef argument type mismatch

 Copy code hover
[image]

ByRef argument type mismatch
Send feedback

An argument passed ByRef (by reference), the default, must have the precise data type expected in the procedure. This error has the following cause and solution:

  • You passed an argument of one type that could not be coerced to the type expected.

    For example, this error occurs if you try to pass an Integer variable when a Long is expected. If you want coercion to occur, even if it causes information to be lost, you can pass the argument in its own set of parentheses. For example, to pass the Variant argument MyVar to a procedure that expects an Integer argument, you can write the call as follows:

    Copy code Copy code
     Dim MyVar
MyVar = 3.1415
Call SomeSub((MyVar))

Sub SomeSub (MyNum As Integer)
MyNum = MyNum + MyNum
End Sub

    Placing the argument in its own set of parentheses forces evaluation of it as an expression. During this evaluation, the fractional portion of the number is rounded (not truncated) to make it conform to the expected argument type. The result of the evaluation is placed in a temporary location, and a reference to the temporary location is received by the procedure. Thus, the original MyVar retains its value.

    Note Note

    If you don't specify a type for a variable, the variable receives the default type, Variant. This isn't always obvious. For example, the following code declares two variables, the first, MyVar, is a Variant; the second, AnotherVar, is an Integer.
VBA Copy code Copy code
Dim MyVar, AnotherVar As Integer

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Calling convention not supported by Visual Basic

 Copy code hover
[image]

Calling convention not supported by Visual Basic
Send feedback

Visual Basic doesn't support all procedure calling conventions, which specify the order in which arguments must be passed and the way that argument types must be specified. This error has the following cause and solution:

  • The procedure was called using a calling convention that Visual Basic doesn't support. For example, Visual Basic doesn't support the Pascal calling convention in a 16-bit version of the Microsoft Windows environment. If the calling convention isn't supported by Visual Basic, the procedure can't be called from Visual Basic. Check the object's documentation to see if an alternative is provided.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Cannot define a KWID_tkPUBLIC user-defined type within a private object module

 Copy code hover
[image]

Cannot define a KWID_tkPUBLIC user-defined type within a private object module
Send feedback

A user-defined type that appears within an object module can't be Public. This error has the following cause and solution:

  • You tried to define a Public user-defined type in an object module. Move the user-defined type definition to a standard module, and then declare variables of the type in the object module or other modules, as appropriate. If you only want the type to be available in the module in which it appears, you can place its Type...End Type definition in the object module and precede its definition with the Private keyword.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Cannot display specified name because it is hidden

 Copy code hover
[image]

Cannot display specified name because it is hidden
Send feedback

Some names exist in a type library, but are marked as hidden. This error has the following causes and solutions:

  • You specified a name that is in the type library, but it is marked as hidden. You cannot normally view hidden type library members. Choose Show Hidden Members on the object browser context menu to make hidden members visible. You can then view the member information.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Cannot handle events for the object specified

 Copy code hover
[image]

Cannot handle events for the object specified
Send feedback

This error has the following causes and solutions:

  • Events for this object could not be handled. The events may be missing from the object, or present and malfunctioning, or intentionally disabled. Check the object and its events in the Object Browser to get information on the object and its events.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Cannot jump to specified type because it is in the specified library, which is not currently referenced

 Copy code hover
[image]

Cannot jump to specified type because it is in the specified library, which is not currently referenced
Send feedback

This error has the following causes and solutions:

  • You tried to specify a type in a library that isn't reference within the project. Set a reference to the type library through the References dialog.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't add a reference to the specified file

 Copy code hover
[image]

Can't add a reference to the specified file
Send feedback

Not all object libraries or type libraries can be accessed by Visual Basic. This error has the following cause and solution:

  • You tried to use the Add References dialog box to add a reference to a type library or object library that can't be used by Visual Basic. Check the documentation for the object represented by the library to see if it's available in some other form that Visual Basic can use.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't assign or coerce array of fixed-length string or user-defined type to Variant

 Copy code hover
[image]

Can't assign or coerce array of fixed-length string or user-defined type to Variant
Send feedback

A Variant can only accept assignment of data having a valid VarType. This error has the following causes and solutions:

  • You tried to pass an array of fixed-length strings. When a single fixed-length string is assigned to a Variant, it's coerced to a variable-length string, but this can't be done for an array of fixed-length strings.

    If you must pass the array, use a loop to assign the individual elements of the array to the elements of a temporary array of variable-length strings. You can then assign the array to a variant and use Erase to deallocate the temporary array. However, you can't deallocate a fixed-size array with Erase.

  • You tried to pass a fixed-length string or user-defined type to the VarType function or TypeName function.

    An argument to the VarType or TypeName function must be a valid Variant type.

  • You tried to assign a user-defined type to a Variant variable. Although you can't directly assign a whole variable of user-defined type to a Variant, you can use the Array function to assign the individual elements of a variable of user-defined type to a Variant. This produces a Variant containing an array of variants. The VarType of each element in this array of variants corresponds to the original type of each element of the user-defined type.

  • You tried to pass an array of fixed-length strings or user-defined types as an argument in a procedure call that requires a Variant argument. Note that any time a procedure is late bound, that is, when the call must be constructed at run time, all arguments must be passed as Variant types. For example, the following code causes this error:

    Copy code Copy code
    Dim MyForm As Object    ' Because MyForm is Object, binding is late.
Set MyForm = New Form1
Dim StringArray(10) As String * 12
' The next line generates the error.
MyForm.MyProc StringArray

    For the string array, use a loop to assign each individual member of the array to a temporary array of variable-length strings. You can then assign that array to a Variant to pass to the procedure. For an array of user-defined types, you can use the Array function to assign the individual elements of a variable of user-defined type to a Variant. This produces a Variant containing an array of variants. The VarType of each element in this array of variants corresponds to the original type of each element of the user-defined type.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't assign to an array

 Copy code hover
[image]

Can't assign to an array
Send feedback

Each element of an array must have its value assigned individually. This error has the following causes and solutions:

  • You inadvertently tried to assign a single value to an array variable without specifying the element to which the value should be assigned.

    To assign a single value to an array element, you must specify the element in a subscript. For example, if MyArray is an integer array, the expression MyArray = 5 is invalid, but the following expression is valid: MyArray(UBound(MyArray)) = 5

  • You tried to assign a whole array to another array.

    For example, if Arr1 is an array and Arr2 is another array, the following two assignments are both invalid:

    Copy code Copy code
    Arr1 = Arr2    ' Invalid assignment.
Arr1() = Arr2()    ' Invalid assignment.

    To assign one array to another, make sure the array on the left-hand side of the assignment is resizable and the types of the array match.

    Note Note

    You can place a whole array in a Variant, resulting in a single variant variable containing the whole array:
    Copy code Copy code
    Dim MyArr As Variant
MyVar = Arr2()

    You then reference the elements of the array in the variant with the same subscript notation as for a normal array, for example:

    Copy code Copy code
    MyVar(3) = MyVar(1) + MyVar(5)

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't call Friend procedure on an object that isn't an instance of the defining class (Error 97)

 Copy code hover
[image]

Can't call Friend procedure on an object that isn't an instance of the defining class (Error 97)
Send feedback

A Friend procedure is callable from a module that is outside the class, but part of the project within which the class is defined. This error has the following causes and solutions:

  • You tried to call the Friend procedure of a class. Although your reference variable is of the proper type, the variable points to an instance that isn't an instance of the class. For example, this can occur if there are two classes, classics and classy (that implements classy), but you mistakenly assign the instance of classy to the instance of classics.

  • You tried to access a Friend property or method either cross-process or cross-thread. Friend procedures are not part of a class's public interface, so they cannot be marshaled cross-process or cross-thread.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't change data types of array elements

 Copy code hover
[image]

Can't change data types of array elements
Send feedback

ReDim can only be used to change the number of elements in an array. This error has the following cause and solution:

  • You tried to redeclare the data type of an array using ReDim.

    Declare a new array of the type you want, and then use the conversion functions to assign each element of the old array to the corresponding element of the new array.

    You can also place the array in a Variant variable. This can be done with a simple assignment:

    Copy code Copy code
    Dim MyVar As Variant
MyVar = MyIntegerArray()

    This creates a Variant containing an array tagged as the type of the original array. You can then assign variables of any valid VarType to the elements of the array within a variant.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't create AutoRedraw image (Error 480)

 Copy code hover
[image]

Can't create AutoRedraw image (Error 480)
Send feedback

Visual Basic can't create a persistent bitmap for automatic redraw of the form or picture. This error has the following cause and solution:

  • There isn't enough available memory for the AutoRedraw property to be set to True. Set the AutoRedraw property to False and perform your own redraw in the Paint event procedure, or make the PictureBox control or Form object smaller and try the operation again with AutoRedraw set to True.


Can't create necessary temporary file (Error 322)

 Copy code hover
[image]

Can't create necessary temporary file (Error 322)
Send feedback

Creating an executable file requires creation of temporary files. This error has the following cause and solution:

  • The drive that contains the directory specified by the TEMP environment variable is full. Delete files from the full drive or specify a different drive in the TEMP environment variable.

  • The TEMP environment variable specifies an invalid or read-only drive or directory. Specify a valid drive for the TEMP environment variable or remove the read-only restriction from the currently specified drive or directory.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't display hidden procedure

 Copy code hover
[image]

Can't display hidden procedure
Send feedback

Everything in a hidden module is hidden. This error has the following cause and solution:

  • You tried to view a procedure in a hidden module.

    Unhide the module to view the procedure. To view a line that generated an error in a hidden procedure, run the code after unhiding the module to view the error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't display system information

 Copy code hover
[image]

Can't display system information
Send feedback

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


Can't edit module

 Copy code hover
[image]

Can't edit module
Send feedback

Modules marked as protected can be viewed, but not edited. This error has the following cause and solution:

  • You tried to edit a protected module. Remove the protection from the module, and then try editing again. In most cases, this error occurs because the Visual SourceSafe addin is installed and the file isn't checked out.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't empty Clipboard (Error 520)

 Copy code hover
[image]

Can't empty Clipboard (Error 520)
Send feedback

The Clipboard was opened but could not be emptied. This error has the following cause and solution:

  • Another application is using the Clipboard and won't release it to your application. Set an error trap for this situation in your code and provide a message box with Retry and Cancel buttons to allow the user to try again after a short pause.


Can't enter break mode at this time

 Copy code hover
[image]

Can't enter break mode at this time
Send feedback

Break mode is the state in which a program is still running, but its activity is suspended. This error has the following cause and solution:

  • You tried to enter break mode, for example, by pressing CTRL+BREAK, pressing the Break button on the Standard toolbar or the Debug toolbar, or by executing a breakpoint in the running code.

    A change was made programmatically to the project using the extensibility (add-in) object model. This prevents the program from having execution suspended. You can continue running, or end execution, but can't suspend execution.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't execute code in break mode

 Copy code hover
[image]

Can't execute code in break mode
Send feedback

You enter break mode when you suspend execution of code. This error has the following causes and solutions:

  • You tried to run code from the Macro dialog box. However, Visual Basic was already running code, although the code was suspended in break mode. You may have entered break mode without knowing it, for example, if a syntax error or run-time error occurred. Continue running the suspended code, or terminate its execution before you run code from the Macro dialog box. You can fix the error and choose Continue, or you can return to the Macro dialog box and restart the macro.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't execute immediate statements in design mode

 Copy code hover
[image]

Can't execute immediate statements in design mode
Send feedback

Design time is any time that your code isn't being executed, or is suspended and waiting to be continued. This error has the following cause and solution:

  • You tried to execute a statement in the Immediate window, but your code isn't in a running mode. Start your code running, and then suspend program execution. You can then execute code in the Immediate window.

For additional information, place the cursor in the Immediate window and press F1 (in Windows) or HELP (on the Macintosh).


Can't exit design mode because control can't be created

 Copy code hover
[image]

Can't exit design mode because control can't be created
Send feedback

All controls must be instantiated before you can exit design mode. This error has the following causes and solutions:

  • The control specified in the error message dialog box could not be created. Code can only run after all controls are instantiated and properly connected. Make sure every file needed for the control is available before trying again.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't find DLL entry point in specified DLL

 Copy code hover
[image]

Can't find DLL entry point in specified DLL
Send feedback

An entry point is the name of a DLL (Windows) or code resource (Macintosh) procedure or the ordinal representing the procedure. This error has the following causes and solutions:

  • A type library incorrectly described the entry point, perhaps misspelling the name or specifying the ordinal incorrectly.

    Contact the vendor for a corrected type library.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't find project or library

 Copy code hover
[image]

Can't find project or library
Send feedback

You can't run your code until all missing references are resolved. This error has the following causes and solutions:

  • A referenced project could not be found, or a referenced object library corresponding to the language of the project could not be found.

    Unresolved references are prefixed with MISSING in the References dialog box. Select the missing reference to display the path and language of the missing project or library. Follow these steps to resolve the reference or references:

To resolve the references

  1. Display the References dialog box.

  2. Select the missing reference.

  3. Start the Object Browser.

  4. Use the Browse dialog box to find the missing reference.

  5. Click OK.

  6. Repeat the preceding steps until all missing references are resolved.

Once you find a missing item, the MISSING prefix is removed to indicate that the link is reestablished. If the file name of a referenced project has changed, a new reference is added, and the old reference must be removed.

To remove a reference that is no longer required, simply clear the check box next to the unnecessary reference. Note that the references to the Visual Basic object library and host-application object library can't be removed.

Applications may support different language versions of their object libraries. To find out which language version is required, click the reference and check the language indicated at the bottom of the dialog box.

Object libraries may be standalone files with the extension .OLB or they can be integrated into a dynamic-link library (DLL) They can exist in different versions for each platform. Therefore, when projects are moved across platforms, for example, from Macintosh to Microsoft Windows, the correct language version of the referenced library for that platform must be available in the location specified in your host application documentation.

Object library file names are generally constructed as follows:

  • Windows (version 3.1 and earlier): Application Code + Language Code + [Version].OLB. For example: The object library for French Visual Basic for Applications, Version 2 was vafr2.olb. The French Microsoft Excel 5.0 object library was xlfr50.olb.

  • Macintosh: Application Name Language Code [Version] OLB. For example: The object library for French Visual Basic for Applications, Version 2 was VA FR 2 OLB. The French Microsoft Excel 5.0 object library was MS Excel FR 50 OLB.

If you can't find a missing project or library on your system, contact the referencing project's author. If the missing library is a Microsoft application object library, you can obtain it as follows:

  • If you have access to Microsoft electronic technical support services, refer to the technical support section of this Help file. Under electronic services, you will find instructions on how to use the appropriate service option.

  • If you don't have access to Microsoft electronic technical support services, Microsoft object libraries are available upon request as an application note from Microsoft. Information on how to contact your local Microsoft product support organization is also available in the technical support section of this Help file.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't find Windows Help .exe file

 Copy code hover
[image]

Can't find Windows Help .exe file
Send feedback

The Windows Help application isn't available. If the MSDN library viewer is on your computer, make sure it is on your path. If it isn't on your computer, you must install it before you can view Help.


Can't Get or Put user-defined type containing object reference

 Copy code hover
[image]

Can't Get or Put user-defined type containing object reference
Send feedback

An object reference is temporary and can easily become invalid between closing and opening a file. This error has the following cause and solution:

  • The variable in your Get or Put statement contains, or is declared to contain, a reference to an object.

    If the variable is an object reference you can't use it with Get and Put statements. To place the value of some or all of the object's properties in the file, each property must be individually specified.

  • The user-defined type variable in your Get or Put statement contains an element that is an object reference.

    If the variable's Type statement contains an element representing an object (for example, it is defined in a class module, has Object data type, is a form or a control, and so on), remove it from the definition, or define a new type for use with the Get and Put statements that has no Object type element in its definition.

    If you have elements in the user-defined type with Variant type, make sure no object reference is assigned to that element. A Variant can accept such an assignment, but will cause this error if its user-defined type is used in a Get or Put.

    Note that you can use Input #, Line Input #, Print #, or Write # to write the default property of an object to disk.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't have paramarrays with optional arguments

 Copy code hover
[image]

Can't have paramarrays with optional arguments
Send feedback

You can use a ParamArray to define procedures that accept variable-length argument lists. An Optional argument is one that the caller can supply or omit without generating an error. This error has the following causes and solutions:

  • You used both the ParamArray and Optional keywords in the same parameter list. Remove either the Optional or ParamArray parameter. You cannot use both keywords in the same parameter list. Either approach can be used for the type of parameter list you want.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't load module; invalid format

 Copy code hover
[image]

Can't load module; invalid format
Send feedback

A module must be in text format. This error has the following cause and solution:

  • You attempted to load a binary format file as a module. Some versions of Visual Basic permit you to save code in both binary and text formats. If possible, reload the file in the application in which it was last saved and save it as text.

For additional information, select the item in question and press F1(in Windows) or HELP (on the Macintosh).


Can't load or unload this object (Error 361)

 Copy code hover
[image]

Can't load or unload this object (Error 361)
Send feedback

A Load statement or Unload statement has referenced an invalid object or control. This error has the following causes and solutions:

  • You tried to load or unload an object that isn't a loadable object, such as Screen, Printer, or Clipboard. Delete the erroneous statement from your code.

  • You tried to load or unload an existing control that isn't part of a control array. For example, assuming that a TextBox with the Name property Text1 exists, Load Text1will cause this error.

    Delete the erroneous statement from your code or change the reference to a control in a control array.

  • You tried to unload a Menu control in the Click event of its parent menu. Unload the Menu control with some other procedure.

  • You tried to unload the last visible menu item of a Menu control. Check the setting of the Visible property for the other menu items in the control array before trying to unload a menu item, or delete the erroneous statement from your code.


Can't make an assignment to a read-only property

 Copy code hover
[image]

Can't make an assignment to a read-only property
Send feedback

Some properties can't accept assignments. This error has the following cause and solution:

  • You tried to assign a value to a property that can't accept assignment. In some cases, a property can accept assignment only at specific times. For example, a property might accept assignments at design time, but not at run time. Check the Help for the specific property to see when it can accept assignments, if ever.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't open Clipboard (Error 521)

 Copy code hover
[image]

Can't open Clipboard (Error 521)
Send feedback

The Clipboard has already been opened by another application. This error has the following cause and solution:

  • Another application is using the Clipboard and won't release it to your application. Set an error trap for this situation in your code and provide a message box with Retry and Cancel buttons to allow the user to try again after a short pause.


Can't perform operation because the project is protected

 Copy code hover
[image]

Can't perform operation because the project is protected
Send feedback

When a project is protected, certain actions are prohibited. This error has the following cause and solution:

  • The project was inadvertently protected. Remove the protection, and then try the action again.

  • The project was intentionally protected. Don't attempt the action until the protection is removed by the person that applied it in the first place.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't perform requested operation (Error 17)

 Copy code hover
[image]

Can't perform requested operation (Error 17)
Send feedback

An operation can't be carried out if it would invalidate the current state of the project. This error has the following cause and solution:

  • The requested operation would invalidate the current state of the project. For example, the error occurs if you use the References dialog box to add a reference to a new project or object library while a program is in break mode.

    Stop execution of the current code, and then retry the operation.

  • An attempt was made to programmatically modify currently running code. For example, your code may have tried to read code from a disk file into a currently running module.

    Although you can modify modules in the project while they aren't actually running, you can't make modifications to a running module. To make such changes, you must stop the module from running, make the additions or changes, and then restart execution.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't perform requested operation since the module is hidden

 Copy code hover
[image]

Can't perform requested operation since the module is hidden
Send feedback

This error pertains to the Visual Basic extensibility (add-in) object model. This error has the following cause and solution:

  • The module is hidden. You can't modify a hidden module or obtain information from a hidden module.

    Unhide the module and try the operation again.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't place conditional breakpoint on an array

 Copy code hover
[image]

Can't place conditional breakpoint on an array
Send feedback

An array has no single value associated with it. This error has the following cause and solution:

  • You tried to set a conditional breakpoint (sometimes called a watchpoint) that would suspend program execution when the value of a whole array changed.

    Set the conditional breakpoint on a specific element of the array.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't print form image to this type of printer (Error 486)

 Copy code hover
[image]

Can't print form image to this type of printer (Error 486)
Send feedback

You must have a graphics-capable printer to print a form image.


Can't print minimized form image

 Copy code hover
[image]

Can't print minimized form image
Send feedback

This error has the following causes and solutions:

  • The form image cannot be printed when it's minimized. Maximize the image and attempt the print operation again.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't quit at this time

 Copy code hover
[image]

Can't quit at this time
Send feedback

You can't quit Windows while Visual Basic is in run mode or break mode. You also can't quit Windows while a dialog box or message box is displayed.


Can't record into running module

 Copy code hover
[image]

Can't record into running module
Send feedback

You must end execution to begin recording. This error has the following cause and solution:

  • You tried to record a macro while executing module code. Stop execution or press CTRL+BREAK (Windows) or COMMAND+PERIOD (Macintosh) and then turn on recording.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't ReDim, Erase, or assign to Variant that contains array whose element is With object

 Copy code hover
[image]

Can't ReDim, Erase, or assign to Variant that contains array whose element is With object
Send feedback

This error has the following causes and solutions:

  • You've attempted to ReDim, Erase, or assign to a Variant a variable whose element is a With object. For example, the following code produces this error:

    Type Test Name as Integer End Type Sub Main() Dim c(0) As Test Dim e e = c With e(0) ReDim e(1) End With End Sub

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't remove control or reference; in use

 Copy code hover
[image]

Can't remove control or reference; in use
Send feedback

The ActiveX control or reference that you tried to remove, is being used by one of the forms in the project. First delete the control or referenced object from the form, and then cancel the selection in the list.


Can't remove default reference

 Copy code hover
[image]

Can't remove default reference
Send feedback

A default reference always exists. This error has the following cause and solution:

  • You tried to remove a reference that must always be available, for example, a type-library or object-library reference.

    Don't attempt to remove the reference.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't rename with different drive (Error 74)

 Copy code hover
[image]

Can't rename with different drive (Error 74)
Send feedback

The Name statement must rename the file to the current drive. This error has the following cause and solution:

  • You tried to move a file to a different drive using the Name statement. Use FileCopy to write the file to another drive, and then delete the old file with a Kill statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't save file to TEMP directory (Error 735)

 Copy code hover
[image]

Can't save file to TEMP directory (Error 735)
Send feedback

Components often need to save temporary information to disk. This error has the following cause and solution:

  • Component can't find a directory named TEMP. Create a directory named TEMP and set the TEMP environment variable equal to its path.

  • The drive or partition containing the TEMP directory lacks sufficient space to save information. Make some space on the drive by erasing unnecessary files, or create a TEMP directory on another partition and set the TEMP environment variable equal to its path.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't set the project name at this time

 Copy code hover
[image]

Can't set the project name at this time
Send feedback

The project name can't be set at this time.


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

 Copy code hover
[image]

Can't show non-modal form when modal form is displayed
Send feedback

This error has the following causes and solutions:

  • You've attempted to show a non-modal form before dismissing a modal form. Dismiss the modal form first.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't sink this object's events because it's already firing events to the maximum number of supported event recipients (Error 96)

 Copy code hover
[image]

Can't sink this object's events because it's already firing events to the maximum number of supported event recipients (Error 96)
Send feedback

Each object specifies the maximum number of simultaneous recipients to which it can fire events. This error has the following causes and solutions:

  • You tried to use Set for a WithEvents variable for a control on a form. You can't use Set for a WithEvents variable because the number of recipients allowed for these events.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't start new recording until current session is ended

 Copy code hover
[image]

Can't start new recording until current session is ended
Send feedback

You can't "nest" recordings. This error has the following cause and solution:

  • You already have the recorder running. Terminate the current recording before beginning a new one

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


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

 Copy code hover
[image]

Can't use character device names in file names: 'item' (Error 320)
Send feedback

From within Visual Basic, you can't give a file the same name as a character device driver. This error has the following cause and solution:

  • You tried to use a file name such as AUX, CON, COM1, COM2, LPT1, LPT2, LPT3, LPT4, or NUL. Give the file another name.


Case Else outside Select Case

 Copy code hover
[image]

Case Else outside Select Case
Send feedback

A Case Else statement can only occur between matching Select Case and End Select statements. This error has the following cause and solution:

  • You placed a Case Else statement outside the Select Case...End Select block. Move the Case Else statement within a Select Case...End Select block.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Case without Select Case

 Copy code hover
[image]

Case without Select Case
Send feedback

A Case statement must occur within a Select Case...End Select Block. This error has the following cause and solution:

  • A Case statement can't be matched with a preceding Select Case statement. Check other control structures within the Select Case...Case structure and verify that they are correctly matched. For example, an If without a matching End If inside the Select Case...End Select structure generates this error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Circular dependencies between modules

 Copy code hover
[image]

Circular dependencies between modules
Send feedback

Circular references between modules, constants, and user-defined types aren't allowed. This error has the following cause and solution:

  • A user-defined type or constant in one module references a user-defined type or constant in a second module, which in turn references another user-defined type or constant in the first module. Remove the dependent references.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Class doesn't support Automation (Error 430)

 Copy code hover
[image]

Class doesn't support Automation (Error 430)
Send feedback

Not all objects expose an Automation interface. This error has the following cause and solution:

  • The class you specified in the GetObject or CreateObject function call was found, but has not exposed a programmability interface.

    You can't write code to control an object's behavior unless it has been exposed for Automation. Check the documentation of the application that created the object for limitations on the use of Automation with this class of object.

  • You changed a project from .dll to .exe, or vice versa. If, for example, you have a .dll server already compiled and registered, and then you change the project type to .exe and recompile it, the fact that the .dll and .exe are already registered on your system prevents you from creating either object. You must manually unregister the old .dll or .exe to avoid the problem. This is caused by the combination of project compatibility and changing a project from an .exe to a .dll. In project compatibility, the CLSID is preserved, but not the IID. Since the CLSID is preserved, the class ends up being registered with two servers — one an in-process server, the other a local server. When an instance is created, the in-process one is chosen. When the querying of the interface occurs, the .dll does not support the IID because it's new.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Class is not set (Error 31018)

 Copy code hover
[image]

Class is not set (Error 31018)
Send feedback

If you don't specify a source document (SourceDoc property) when setting Action = 0 (CreateEmbed method), the Class property must be set to the name of a class available on your system.

To display a list of the available class names at design time, right-click the OLE container control and choose the Insert Object command.


Class not registered on local machine (Error 463)

 Copy code hover
[image]

Class not registered on local machine (Error 463)
Send feedback

The CreateObject function requires a valid server. This error has the following cause and solution:

  • A server parameter was specified, but the specified class progid (the first parameter of the CreateObject function) is not registered on the local system.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Class not registered. 'item 1'

 Copy code hover
[image]

Class not registered. 'item 1'
Send feedback

This error has the following causes and solutions:

  • The indicated class module is not registered.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Code execution has been interrupted

 Copy code hover
[image]

Code execution has been interrupted
Send feedback

Code execution can be suspended when necessary. This condition has the following cause and solution:

  • A CTRL+BREAK (Microsoft Windows), ESC (Microsoft Excel) or COMMAND+PERIOD (Macintosh) key combination has been encountered. In the error dialog box, click Debug to enter break mode, Continue to resume, or End to stop execution.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Code resource lock error (Error 455)

 Copy code hover
[image]

Code resource lock error (Error 455)
Send feedback

This error can only occur on the Macintosh. When you access a code resource, you must lock it. This error has the following cause and solution:

  • A call was made to a procedure in a code resource. The code resource was found, but an error occurred when an attempt was made to lock the resource.

    Check for an error returned by Hlock, for example, "Illegal on empty handle" or "Illegal on free block".

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Code resource not found (Error 454)

 Copy code hover
[image]

Code resource not found (Error 454)
Send feedback

This error can only occur on the Macintosh. This error has the following cause and solution:

  • A call was made to a procedure in a code resource, but the code resource could not be found.

    Check to be sure the resource is available and properly referenced.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Compile error in hidden module:

 Copy code hover
[image]

Compile error in hidden module: <module name>
Send feedback

A protected module contains a compilation error. Because the error is in a protected module it cannot be displayed.

This error commonly occurs when code is incompatible with the version or architecture of this application (for example, code in a document targets 32-bit Microsoft Office applications but it is attempting to run on 64-bit Office).

This error has the following cause and solution:

Cause of the error:

  • The error is raised when a compilation error exists in the VBA code inside a protected (hidden) module. The specific compilation error is not exposed because the module is protected.

Possible solutions:

  • If you have access to the VBA code in the document or project, unprotect the module, and then run the code again to view the specific error.

  • If you do not have access to the VBA code in the document, then contact the document author to have the code in the hidden module updated.


Component could not successfully create requested object

 Copy code hover
[image]

Component could not successfully create requested object
Send feedback

This error has the following causes and solutions:

  • The ActiveX component's executable (.exe) file failed to run correctly. There may be a problem with the information in the registry.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Component 'item' or one of its dependencies not correctly registered: a file is missing or invalid

 Copy code hover
[image]

Component 'item' or one of its dependencies not correctly registered: a file is missing or invalid
Send feedback

This error has the following causes and solutions:

  • The specified file was moved or deleted.

  • The specified file was incorrectly registered. Reinstall the specified file to correctly register it. See the object's vendor for more information.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Component not correctly registered

 Copy code hover
[image]

Component not correctly registered
Send feedback

This error has the following causes and solutions:

  • The indicated component was not correctly registered.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Component not found in registered location

 Copy code hover
[image]

Component not found in registered location
Send feedback

This error has the following causes and solutions:

  • The required executable file (.exe) or dynamic-link library (.dll) file can't be found.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Conflicting attributes were found in 'item'. The defaults will be used

 Copy code hover
[image]

Conflicting attributes were found in 'item'. The defaults will be used
Send feedback

Some of the attribute statements in a form, User Control, Property Page, User Document, or Class Module conflict with the required settings for their type. For example, forms must always have the VB_PredeclaredId attribute equal to True. This error can occur if the file was modified by an editor other than Visual Basic.


Conflicting names were found in 'item1'. The name 'item2' will be used

 Copy code hover
[image]

Conflicting names were found in 'item1'. The name 'item2' will be used
Send feedback

The name of a form occurs twice in the source file for a form, User Control, Property Page, or User Document. This error can occur if the file was modified by an editor other than Visual Basic.


Connection to type library or object library for remote process has been lost (Error 442)

 Copy code hover
[image]

Connection to type library or object library for remote process has been lost (Error 442)
Send feedback

During remote access (that is, when accessing an object that is part of another process or is running on another machine), the connection to the library containing object information was broken. This error has the following cause and solution:

  • You lost your connection to the remote process's object library or type library.

    To reconnect, follow these steps:

    1. Restart the Application object.

    2. In the error dialog box through which you entered this Help topic, click OK to display the References dialog box.

    3. The lost reference appears with the word MISSING to its left.

    4. Remove the lost reference.

    5. In the References dialog box, click the check box for the object you started in step 1.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Constant expression required

 Copy code hover
[image]

Constant expression required
Send feedback

A constant must be initialized. This error has the following causes and solutions:

  • You tried to initialize a constant with a variable, and instance of a user-defined type, an object, or the return value of a function call.

    Initialize constants with literals, previously declared constants, or literals and constants joined by operators (except the Is logical operator).

  • array

    To declare a dynamic array within a procedure, declare the array with ReDim and specify the number of elements with a variable.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Constants, fixed-length strings, arrays, user-defined types, and Declare statements not allowed as Public members of an object module

 Copy code hover
[image]

Constants, fixed-length strings, arrays, user-defined types, and Declare statements not allowed as Public members of an object module
Send feedback

Not all variables in an object module can be declared as Public. However, procedures are Public by default, and Property procedures can be used to simulate variables syntactically. This error has the following causes and solutions:

  • You declared a Public constant in an object module.

    Although you can't declare a Public constant in an object module, you can create a Property Get procedure with the same name. If you don't create a Property Let or Property Set procedure with that name, you are in effect creating a read-only property that can be used the same way you would use a constant.

  • You declared a Public fixed-length string in an object module. You can simulate fixed-length strings with a set of Property procedures that either truncate the string data when it exceeds the permitted length, or notify the user that the length has been exceeded.

  • You declared a Public array in an object module.

    Although a procedure can't return an array, it can return a Variant that contains an array. To simulate a Public array in a class module, use a set of Property procedures that accept and return a Variant containing an array.

  • You placed a Declare statement in an object module. Declare statements are implicitly public. Precede the Declare statement with the Private keyword.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Could not access system registry (Error 335)

 Copy code hover
[image]

Could not access system registry (Error 335)
Send feedback

An attempt to read from or write to the system registry failed.


Could not create reference: 'item'

 Copy code hover
[image]

Could not create reference: 'item'
Send feedback

There was an error establishing a reference while loading the file, so the reference was not added.


Could not execute specified program

 Copy code hover
[image]

Could not execute specified program
Send feedback

When you create a native-code executable file, some extra programs must run. This error has the following causes and solutions:

  • Memory or system resources were insufficient to run the code generator or linker. Close as many running applications as possible to free memory and other system resources.

  • Visual Basic was installed incorrectly. Reinstall Visual Basic.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Could not start Internet Explorer

 Copy code hover
[image]

Could not start Internet Explorer
Send feedback

This error has the following causes and solutions:

  • An unknown problem is preventing Internet Explorer from running. Try starting Internet Explorer on its own to make sure it's working correctly.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Current module does not support Print method

 Copy code hover
[image]

Current module does not support Print method
Send feedback

Not all methods and properties are appropriate in all modules. This error has the following causes and solutions:

  • You tried to use the Print method on an object that can't display anything. For example, you can't use the Print method without qualification in a standard module.

    Remove the reference to the Print method, or qualify it with an appropriate object. For example, qualify it with the Debug object to display its arguments in the Immediate window during debugging.

  • You tried to use the Line, Circle, PSet, or Scale method on an object that can't accept them. For example, they can't appear unqualified in a standard module or an Automation class module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Cyclic reference of projects not allowed

 Copy code hover
[image]

Cyclic reference of projects not allowed
Send feedback

Circular references to projects aren't allowed. For example, if MyProj references YourProj , then YourProj (or a project that references YourProj ) can't reference references YourProj , then YourProj (or a project that references YourProj ) can't reference MyProj . This error has the following cause and solution:

  • You tried to add a reference to a project that is already part of the project. Remove the circular reference or references.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Data value named not found (Error 327)

 Copy code hover
[image]

Data value named not found (Error 327)
Send feedback

The data value could not be found.


Definitions of property procedures for the same property are inconsistent

 Copy code hover
[image]

Definitions of property procedures for the same property are inconsistent
Send feedback

The parameters for Property Get, Property Let, and Property Set procedures for the same property must match exactly, except that the Property Let has one extra parameter, whose type must match the return type of the corresponding Property Get, and the Property Set has one more parameter than the corresponding Property Get, whose type is either Variant, Object, a class name, or an object library type specified in an object library. This error has the following causes and solutions:

  • The number of parameters for the Property Get procedure isn't one less than the number of parameters for the matching Property Let or Property Set procedure. Add a parameter to Property Let or Property Set or remove a parameter from Property Get, as appropriate.

  • The parameter types of Property Get must exactly match the corresponding parameters of Property Let or Property Set, except for the extra Property Set parameter. Modify the parameter declarations in the corresponding procedure definitions so they are appropriately matched.

  • The parameter type of the extra parameter of the Property Let must match the return type of the corresponding Property Get procedure. Modify either the extra parameter declaration in the Property Let or the return type of the corresponding Property Get so they are appropriately matched.

  • The parameter type of the extra parameter of the Property Set can differ from the return type of the corresponding Property Get, but it must be either a Variant, Object, class name, or a valid object library type.

    Make sure the extra parameter of the Property Set procedure is either a Variant, Object, class name, or object library type.

  • You defined a Property procedure with an Optional or a ParamArray parameter. ParamArray and Optional parameters aren't permitted in Property procedures. Redefine the procedures without using these keywords.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Deftype statements must precede declarations

 Copy code hover
[image]

Deftype statements must precede declarations
Send feedback

Def type statements include DefInt, DefDbl, DefCur, and so on. This error has the following causes and solutions:

  • A variable declaration precedes a Def type statement at module level.

    Move the Def type statement to precede all variable declarations.

  • A Def type statement appears in a procedure.

    Move the Def type statement to module level, preceding all variable declarations.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Destination label too far away; loop, Select Case, or block If too large

 Copy code hover
[image]

Destination label too far away; loop, Select Case, or block If too large
Send feedback

Procedures can be as large as 64K from beginning to end, but because branching can occur either forward or backward within a procedure, such branching is limited to 32,767 bytes in either direction. This error has the following causes and solutions:

  • You have a branching statement (GoTo, GoSub) whose destination label is farther away than 32,767 bytes from the source branching statement. Move the label closer, or make the procedure smaller.

  • You have a very large loop structure that occupies more than 32K of memory from beginning to end. Make the loop smaller.

  • You have a very large block If structure that contains a Then or Else clause that occupies more than 32K of memory from beginning to end. Reduce the size of the offending portion of the structure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Device I/O error (Error 57)

 Copy code hover
[image]

Device I/O error (Error 57)
Send feedback

External devices are sometimes subject to unanticipated errors. This error has the following cause and solution:

  • An input or output error occurred while your program was using a device such as a printer or disk drive. Make sure the device is operating properly, and then retry the operation.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Device unavailable (Error 68)

 Copy code hover
[image]

Device unavailable (Error 68)
Send feedback

This error has the following causes and solutions:

  • The device you are trying to access either is not online or doesn't exist. Check power to the device and any cables connecting your computer to the device. If you are trying to access a printer over a network, make sure there is a logical connection between your computer and the printer, for example, a connection associating LPT1 with the network printer ID.

  • Your network connection may have been broken. Reconnect to the network and try the operation again.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Disk full (Error 61)

 Copy code hover
[image]

Disk full (Error 61)
Send feedback

This error has the following causes and solutions:

  • There isn't enough room on the disk for the completion of a Print #, Write #, or Close operation. Move some files to another disk or delete some files.

  • There isn't enough room on the disk to create required files. Move some files to another disk or delete some files.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Disk not ready (Error 71)

 Copy code hover
[image]

Disk not ready (Error 71)
Send feedback

This error has the following causes and solutions:

  • There is no disk in the specified drive. Put a disk in the drive and retry the operation.

  • The drive door of the specified drive is open. Close the drive door and retry the operation.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Display more load errors?

 Copy code hover
[image]

Display more load errors?
Send feedback

Click OK to see more errors, otherwise click Cancel.


Division by zero (Error 11)

 Copy code hover
[image]

Division by zero (Error 11)
Send feedback

Division by zero isn't possible. This error has the following cause and solution:

  • The value of an expression being used as a divisor is zero.

    Check the spelling of variables in the expression. A misspelled variable name can implicitly create a numeric variable that is initialized to zero. Check previous operations on variables in the expression, especially those passed into the procedure as arguments from other procedures.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Do without Loop

 Copy code hover
[image]

Do without Loop
Send feedback

Each Do must be matched with a terminating Loop. This error has the following cause and solution:

  • A Do statement was used without a terminating Loop statement. Check that other control structures within the Do...Loop structure are correctly matched. For example, a block If without a matching End If inside the Do...Loop structure may generate this error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Do you want to export specified object before removing it?

 Copy code hover
[image]

Do you want to export specified object before removing it?
Send feedback

You can export forms and modules, and reload them at another time. This error has the following cause and solution:

  • You are removing a form or module from the project.

    To preserve the module, export it. You can then import it at a future time.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Duplicate declaration in current scope

 Copy code hover
[image]

Duplicate declaration in current scope
Send feedback

The specified name is already used at this level of scope. For example, two variables can have the same name if they are defined in different procedures, but not if they are defined within the same procedure. This error has the following causes and solutions:

  • A new variable or procedure has the same name as an existing variable or procedure. For example:

    Copy code Copy code
    Sub MySub()
Dim A As Integer
Dim A As Variant
. . .        ' Other declarations or procedure code here.
End Sub

    Check the current procedure, module, or project and remove any duplicate declarations.

  • A Const statement uses the same name as an existing variable or procedure. Remove or rename the constant in question.

  • You declared a fixed array more than once.

    Remove or rename one of the arrays.

Search for the duplicate name. When specifying the name to search for, omit any type-declaration character because a conflict occurs if the names are the same and the type-declaration characters are different.

Note that a module-level variable can have the same name as a variable declared in a procedure, but when you want to refer to the module-level variable within the procedure, you must qualify it with the module name. Module names and the names of referenced projects can be reused as variable names within procedures and can also be qualified.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Duplicate definition

 Copy code hover
[image]

Duplicate definition
Send feedback

You can only define a conditional compiler constant to have one value. This error has the following cause and solution:

  • You specified two different values for the same conditional compiler constant, for example:

    Copy code Copy code
    #Const Mac = 0
#Const Mac = 1

    Remove one of the definitions.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Duplicate Deftype statement

 Copy code hover
[image]

Duplicate Deftype statement
Send feedback

Def type statements in the same scope must specify unique letter ranges. This error has the following cause and solution:

  • Part or all of the letter range for this Def type statement is already included in another Def type statement. Rewrite the statement so there is no overlap in the letter ranges.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Duplicate Option statement

 Copy code hover
[image]

Duplicate Option statement
Send feedback

Only one Option statement of each kind may occur in each module. This error has the following cause and solution:

  • You defined more than one Option Base, Option Compare, Option Explicit, or Option Private statement in this module. Remove any duplicates in the module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Duplicate procedure name

 Copy code hover
[image]

Duplicate procedure name
Send feedback

You defined (or are attempting to define) more than one version of a procedure with the same name. Rename one of the procedures. Ensure duplicate Declare statements for the same procedure have the same Alias clause.


Duplicate resources with same type and name

 Copy code hover
[image]

Duplicate resources with same type and name
Send feedback

A Microsoft Windows resource file typically contains bitmaps, text strings, and other similar data used by an application. This error has the following causes and solutions:

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

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

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Edit can't be undone--proceed anyway?

 Copy code hover
[image]

Edit can't be undone--proceed anyway?
Send feedback

You won't be able to choose the Undo command to restore the current state after you perform this edit. This error has the following cause and solution:

  • This typically occurs when an edit is simply too large to be saved. Try performing the edit in smaller increments.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Else without If

 Copy code hover
[image]

Else without If
Send feedback

An Else must be preceded by an If. This error has the following cause and solution:

  • An Else statement was used without a corresponding If statement. Check other control structures within the If...End If structure and verify that they are correctly matched. Also check that the block If is correctly formatted.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Empty Enum type not allowed

 Copy code hover
[image]

Empty Enum type not allowed
Send feedback

An Enum type specifies the name and members for an enumeration. This error has the following cause and solution:

  • You named an enumeration in an Enum…End Enum block, but failed to specify any members. Add at least one member to the Enum…End Enum block.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Empty watch expression

 Copy code hover
[image]

Empty watch expression
Send feedback

The Add Watch dialog box requires entry of an expression. This error has the following cause and solution:

  • You didn't supply a watch expression in the Add Watch dialog box.

    Add an expression to the Add Watch dialog box or press the ESC key.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


End If without block If

 Copy code hover
[image]

End If without block If
Send feedback

An End If statement must have a corresponding If statement. This error has the following cause and solution:

  • The If clause was omitted or is separated from the End If. Check other control structures within the If...End If structure and verify that they are correctly matched. Also check that the block If is correctly formatted.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


End of search scope has been reached; do you want to continue from the beginning?

 Copy code hover
[image]

End of search scope has been reached; do you want to continue from the beginning?
Send feedback

Your search was unsuccessful. This error has the following cause and solution:

  • Your downward search has reached the end of the specified scope. You can continue searching from the beginning of the search scope, or cancel and change the scope of the search.


End Select without Select Case

 Copy code hover
[image]

End Select without Select Case
Send feedback

End Select must be matched with a preceding Select Case. This error has the following cause and solution:

  • You used an End Select statement without a corresponding Select Case statement. This is usually due to an extra End Select below a Select Case block, or leaving behind the End Select statement when copying a Select Case block from one procedure to another. Check each End Select statement to make sure it terminates a Select Case structure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


End With without With

 Copy code hover
[image]

End With without With
Send feedback

End With must be matched with a preceding With. This error has the following cause and solution:

  • You used an End With statement without a corresponding With statement. Check other control structures within the With...End With structure and verify that they are correctly matched. For example, an If without a matching End If inside the With...End With structure can cause this error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Enum types defined in standard modules or private classes cannot be used in public object modules as parameters or return types for public procedures, as public data members, or as fields of public user defined types

 Copy code hover
[image]

Enum types defined in standard modules or private classes cannot be used in public object modules as parameters or return types for public procedures, as public data members, or as fields of public user defined types
Send feedback

This error has the following cause and solution:

  • A non-exposed enum was used as a parameter or return type of a public procedure or a public data member of an exposed class.

Exposed here means that the enum is exposed from the ActiveX server that is being defined, which is equivalent to saying that it is declared in a public class of an ActiveX Exe or Dll project.


Error accessing the system registry

 Copy code hover
[image]

Error accessing the system registry
Send feedback

Some operations must access your system's registration database. This error has the following cause and solution:

  • The registration database for your system has been corrupted. Run the Setup program for the host application again.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Error in loading DLL (Error 48)

 Copy code hover
[image]

Error in loading DLL (Error 48)
Send feedback

A dynamic link library (DLL) is a library specified in the Lib clause of a Declare statement. This error has the following causes and solutions:

  • The file isn't DLL-executable. If the file is a source-text file, it must be compiled and linked to DLL executable form.

  • The file isn't a Microsoft Windows DLL. Obtain the Microsoft Windows DLL equivalent of the file.

  • The file is an early Microsoft Windows DLL that is incompatible with Microsoft Windows protect mode. Obtain an updated version of the DLL.

  • The DLL references another DLL that isn't present. Obtain the referenced DLL and make it available to the other DLL.

  • The DLL or one of the referenced DLLs isn't in a directory specified by your path. Move the DLL to a referenced directory or place its current directory on the path.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Error loading from file (Error 31037)

 Copy code hover
[image]

Error loading from file (Error 31037)
Send feedback

An error occurred while attempting to read the specified file (set Action = 12). Possible causes:

  • The FileNumber property is invalid.

  • The file wasn't opened in Binary mode.

  • The file wasn't saved properly (set Action = 11).

  • The file is corrupted.

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


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

 Copy code hover
[image]

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

This error message appears after another error has occurred. After you've taken the appropriate action for that error, you will see this error message. To load the control anyway, click Yes; to cancel the loading, click No.


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

 Copy code hover
[image]

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

You may have tried to load a form with controls whose names conflict with forms already in the project. For example, loading Form2 that contains a Form1 control triggers this error.


Error saving to file (Error 31036)

 Copy code hover
[image]

Error saving to file (Error 31036)
Send feedback

Visual Basic can't write the object to the specified file (set Action = 11 or 18). Possible causes:

  • The FileNumber property is invalid.

  • The specified file wasn't opened in Binary mode.

  • There isn't enough disk space.


Errors during load. Refer to 'item' for details

 Copy code hover
[image]

Errors during load. Refer to 'item' for details
Send feedback

Something unexpected appeared in the ASCII form file. Visual Basic created a log file to provide more detail about the errors. You should examine the log file to determine the severity of the problem. Sometimes you can safely ignore the errors (for example, Version number missing or invalid... ). Other times, however, the errors could cause the form not to run as expected (for example, Class MyClass in control MyControl was not a loaded control class.).


Errors occurred during load

 Copy code hover
[image]

Errors occurred during load
Send feedback

Check the error log for more descriptive information.


Event handler is invalid

 Copy code hover
[image]

Event handler is invalid
Send feedback

The parameter list of an event-handling procedure must precisely match the declaration of the event. This error has the following cause and solution:

  • Your event-handling procedure has the wrong number of parameters. Eliminate extra parameters or add the missing ones.

  • One or more of your event-handling procedure parameters has the wrong data type.

    Make the parameter types match those of the event declaration.

  • Your event-handling procedure is a Function rather than a Sub. Make your procedure a Sub. An event handler can't return a value.

  • Another type library uses the event name for a type of its own.

    Qualify the name with the name of the proper type library to avoid the ambiguity.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Event not found

 Copy code hover
[image]

Event not found
Send feedback

An event specified in a RaiseEvent statement must correspond to a defined event. This error has the following causes and solutions:

  • You specified a name in a RaiseEvent statement, but the event definition cannot be found. Make sure the event name is spelled correctly.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Exit Do not within Do...Loop

 Copy code hover
[image]

Exit Do not within Do...Loop
Send feedback

Exit Do is only valid within a Do...Loop statement. This error has the following cause and solution:

  • You used an Exit Do statement outside a Do...Loop statement. Make sure a valid Do statement precedes the Exit Do.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Exit For not within For...Next

 Copy code hover
[image]

Exit For not within For...Next
Send feedback

Exit For is only valid within a For...Next loop. This error has the following cause and solution:

  • You used an Exit For statement outside a For...Next statement. Make sure a valid For statement precedes the Exit For.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Exit Function not allowed in Sub or Property

 Copy code hover
[image]

Exit Function not allowed in Sub or Property
Send feedback

An Exit statement must match the procedure in which it occurs. This error has the following cause and solution:

  • You used Exit Function in a Sub or Property procedure. Use Exit Sub or Exit Property for these types of procedures.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Exit Property not allowed in Function or Sub

 Copy code hover
[image]

Exit Property not allowed in Function or Sub
Send feedback

An Exit statement must match the procedure in which it occurs. This error has the following cause and solution:

  • You used Exit Property in a Sub or Function procedure. Use the proper Exit statement for this type of procedure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Exit Sub not allowed in Function or Property

 Copy code hover
[image]

Exit Sub not allowed in Function or Property
Send feedback

An Exit statement must match the procedure in which it occurs. This error has the following cause and solution:

  • You used Exit Sub in a Function or Property procedure. Use the proper Exit statement for this type of procedure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected array

 Copy code hover
[image]

Expected array
Send feedback

A variable name with a subscript indicates the variable is an array. This error has the following cause and solution:

  • The syntax you specified is appropriate for an array, but no array with this name is in scope.

    Check to make sure the name of the variable is spelled correctly. Unless the module contains Option Explicit, a variable is created on first use. If you misspell the name of an array variable, the variable may be created, but not as an array.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected End Function

 Copy code hover
[image]

Expected End Function
Send feedback

An End procedure statement must match the procedure in which it occurs. This error has the following cause and solution:

  • You used End Property or End Sub to end a Function procedure. Use End Function for this type of procedure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected End Property

 Copy code hover
[image]

Expected End Property
Send feedback

An End procedure statement must match the procedure in which it occurs. This error has the following cause and solution:

  • You used End Function or End Sub to end a Property procedure. Use End Property for this type of procedure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected End Sub

 Copy code hover
[image]

Expected End Sub
Send feedback

An End procedure statement must match the procedure in which it occurs. This error has the following cause and solution:

  • You used End Function or End Property to end a Sub procedure. Use End Sub for this type of procedure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected End With

 Copy code hover
[image]

Expected End With
Send feedback

A With block must be terminated. This error has the following cause and solution:

  • You did not properly terminate a With block. Place an End With statement at the end of the block.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected Function or variable

 Copy code hover
[image]

Expected Function or variable
Send feedback

The syntax of your statement indicates a variable or function call. This error has the following cause and solution:

  • The name isn't that of a known variable or Function procedure.

    Check the spelling of the name. Make sure that any variable or function with that name is visible in the portion of the program from which you are referencing it. For example, if a function is defined as Private or a variable isn't defined as Public, it's only visible within its own module.

  • You are trying to inappropriately assign a value to a procedure name.

    For example if MySub is a Sub procedure, the following code generates this error:

    VBA Copy code Copy code
    MySub = 237    ' Causes Expected Function or variable error

    Although you can use assignment syntax with a Property Let procedure or with a Function that returns an object or a Variant containing an object, you can't use assignment syntax with a Sub, Property Get, or Property Set procedure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected procedure, not module

 Copy code hover
[image]

Expected procedure, not module
Send feedback

There is no procedure by this name in the current scope, but there is a module by this name. You can call a procedure, but not a module. This error has the following cause and solution:

  • The name of a module is used as a procedure call. Check the spelling of the procedure name, and make sure the procedure you are trying to call isn't private to another module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected procedure, not project or library

 Copy code hover
[image]

Expected procedure, not project or library
Send feedback

There is no procedure by this name in the current scope, but there is a project by this name. You can call a procedure, but not a project. This error has the following cause and solution:

  • The name of a project is used as a procedure call. Check the spelling of the procedure name, and make sure the procedure you are trying to call isn't private to another module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected procedure, not user-defined type

 Copy code hover
[image]

Expected procedure, not user-defined type
Send feedback

There is no procedure by this name in the current scope, but there is a user-defined type by this name. You can call a procedure, but not a user-defined type. This error has the following cause and solution:

  • The name of a user-defined type is used as a procedure call. Check the spelling of the procedure name, and make sure the procedure you are trying to call isn't private to another module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected procedure, not variable

 Copy code hover
[image]

Expected procedure, not variable
Send feedback

There is no procedure by this name in the current scope, but there is a variable by this name. You can call a procedure, but not a variable. This error has the following cause and solution:

  • The name of a variable is used as a procedure call. The error may also be caused by misspelling the name of a valid procedure, because that can be misconstrued as an implicitly defined variable. Check the spelling of the procedure name, and make sure the procedure you are trying to call isn't private to another module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected Sub, Function, or Property

 Copy code hover
[image]

Expected Sub, Function, or Property
Send feedback

The syntax of your statement indicates a Sub, Function, or Property procedure invocation. This error has the following cause and solution:

  • The specified name isn't that of a Sub, Function, or Property procedure in scope in this part of your program.

    Check the spelling of the name. Note that if the procedure is defined as Private, it can only be called from within its module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected user-defined type, not project

 Copy code hover
[image]

Expected user-defined type, not project
Send feedback

There is no user-defined type by this name in the current scope, but there is a project by this name. You can define a variable as having user-defined type, but not project type. This error has the following cause and solution:

  • The name of a project is used as a user-defined type. Check the spelling of the name of the user-defined type, and make sure the user-defined type isn't private to another module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected variable or procedure, not Enum type

 Copy code hover
[image]

Expected variable or procedure, not Enum type
Send feedback

The name of an Enum type only appears in a statement declaring an enumeration of the type or as a qualifier. This error has the following cause and solution:

  • An Enum type name is used instead of the name of an enumeration variable of the type. Declare a variable of the Enum type or find a previous declaration in the current scope and use that variable.

  • An Enum type name is used instead of a variable or procedure name.

    Check the spelling of the identifier that caused the error. Use the name of a variable or procedure where you specified an Enum type.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected variable or procedure, not module

 Copy code hover
[image]

Expected variable or procedure, not module
Send feedback

There is no variable or procedure by this name in the current scope, but there is a module by this name. This error has the following cause and solution:

  • The name of a module is used as a variable or procedure. Check the spelling of the variable or procedure name, and make sure the name you want to refer to isn't private to another module. A module name can be a qualifier, but can't stand alone.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected variable or procedure, not project

 Copy code hover
[image]

Expected variable or procedure, not project
Send feedback

There is no variable or procedure by this name in the current scope, but there is a project by this name. This error has the following cause and solution:

  • The name of a project is used as a variable or procedure. Check the spelling of the variable or procedure name, and make sure the name you want to refer to isn't private to another module. A project name can be a qualifier, but can't stand alone.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expected:

 Copy code hover
[image]

Expected: <various>
Send feedback

An expected part of the syntax was not found. The error is usually located to the left of the selected item, but isn't always obvious. For example, you can invoke a Sub procedure with or without the Call keyword. However, if you use the Call keyword, you must enclose the argument list in parentheses. This error has the following causes and solutions:

  • Expected: End of Statement. Improper use of parentheses in a procedure invocation:

    Copy code Copy code
    X = Workbook.Add F:= 5    ' Error due to no parentheses.
Call MySub 5                ' Error due to no parentheses.

    Use parentheses in a function call that specifies arguments or with a Sub procedure invocation that uses the Call keyword.

  • Expected: ). Incorrect syntax for a procedure call. For example, a function call can't stand by itself, and Sub procedure calls sometimes require the Call keyword, depending on how you specify their arguments.

    Copy code Copy code
    Workbook.Add (X:=5, Y:=7)    ' Function call without expression.
YourSub(5, 7)                ' Sub invocation without Call.

    Always use function calls in expressions. If you have multiple arguments enclosed in parentheses in a Sub procedure call, you must use the Call keyword.

  • Expected: Expression. For example, when pasting code from the Object Browser, you may have forgotten to specify a value for a named argument.

    Copy code Copy code
    Workbook.Add (X:= )    ' Error because no value assigned to
' named argument.

    Either add a value for the argument, or delete the argument if it's optional.

  • Expected: Variable. For example, you may have used restricted keywords for variable names. In the following example, the Input # statement expects a variable as the second argument. Since Type is a restricted keyword, it can't be used as a variable name.

    Copy code Copy code
    Input # 1, Type    ' Type keyword invalidly used as
' variable name.

    Rename the variable so it doesn't conflict with restricted keywords.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Expression too complex (Error 16)

 Copy code hover
[image]

Expression too complex (Error 16)
Send feedback

The number of subexpressions allowed in a floating-point expression varies among platforms. For example, on 32-bit Microsoft Windows operating systems, the limit is 8 levels of nested floating-point expressions. This error has the following cause and solution:

  • A floating-point expression contains too many nested subexpressions.

    Break the expression into as many separate expressions as necessary to prevent the error from occurring.

    Note Note

    In earlier versions of Visual Basic, Error 16 was "String expression too complex." That error condition can no longer occur. However, if you have early code that traps and handles that error, you should remove it to prevent confusion with this new error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


External name not defined

 Copy code hover
[image]

External name not defined
Send feedback

You can indicate external names by enclosing them in brackets ([ ]). This error has the following cause and solution:

  • The identifier specified within brackets has no meaning to the host application.

    Check the spelling of the name to be sure it's consistent with that expected by the host.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Failed to activate control 'item 1'. This control may be incompatible with your application. Make sure you are using the version of the control that was provided with your application.

 Copy code hover
[image]

Failed to activate control 'item 1'. This control may be incompatible with your application. Make sure you are using the version of the control that was provided with your application.
Send feedback

This error has the following causes and solutions:

  • The application was unable to activate the indicated control since it was incompatible with the application. This can occur if the version of the control currently on your system is different from that provided with your application.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Failed to load control 'item1' from 'item2'. Your version of 'item2' may be outdated. Make sure you are using the version of the control that was provided with your application.

 Copy code hover
[image]

Failed to load control 'item1' from 'item2'. Your version of 'item2' may be outdated. Make sure you are using the version of the control that was provided with your application.
Send feedback

This error has the following causes and solutions:

  • You are using an outdated version.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


File already exists (Error 58)

 Copy code hover
[image]

File already exists (Error 58)
Send feedback

This error has the following causes and solutions:

  • This error occurs at run time when the new file name, for example, one specified in a Name statement, is identical to a file name that already exists.

    Specify a new file name in the Name statement or delete the old file before specifying it in a Name statement.

  • You used the Save As command to save a currently loaded project, but the project name already exists.

    Use a different project name if you don't want to replace the other project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


File already open (Error 55)

 Copy code hover
[image]

File already open (Error 55)
Send feedback

Sometimes a file must be closed before another Open or other operation can occur. This error has the following causes and solutions:

  • A sequential-output mode Open statement was executed for a file that is already open. You must close a file opened for one type of sequential access before opening it for another. For example, you must close a file opened for Input before opening it for Output.

  • A statement, for example, Kill, SetAttr, or Name, refers to an open file. Close the file before executing the statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


File format no longer supported

 Copy code hover
[image]

File format no longer supported
Send feedback

Not all file formats are readable under all circumstances. This error has the following cause and solution:

  • You are trying to load a binary file created with an earlier version of Visual Basic. Load the file into the version of Visual Basic with which the file was created, save it in text format, then try to load it again.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


File is read-only

 Copy code hover
[image]

File is read-only
Send feedback

The file is not writable. To change it, you must save it under a different name or remove the read-only attribute.


File not found (Error 53)

 Copy code hover
[image]

File not found (Error 53)
Send feedback

The file was not found where specified. This error has the following causes and solutions:

  • A statement, for example, Kill, Name, or Open, refers to a file that doesn't exist. Check the spelling of the file name and the path specification.

  • An attempt has been made to call a procedure in a dynamic-link library (DLL), but the library or resource file name specified in the Lib clause of the Declare statement can't be found.

    Check the spelling of the file name and the path specification.

  • In the development environment, this error occurs if you attempt to open a project or load a text file that doesn't exist.

    Check the spelling of the project name or file name and the path specification.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


File specified was not found

 Copy code hover
[image]

File specified was not found
Send feedback

Check the message for the name of the file that couldn't be found. This error has the following causes and solutions:

  • The file named in the error message could not be found as specified. Make sure the drive name and path, as well as the filename, are specified correctly.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Filename or class name not found during Automation operation (Error 432)

 Copy code hover
[image]

Filename or class name not found during Automation operation (Error 432)
Send feedback

The GetObject function requires either a valid file name with a path specification, or the name of a class that is registered with the system. This error has the following cause and solution:

  • The name specified for file name or class in a call to the GetObject function could not be found. Check the names and try again. Make sure the name used for the class parameter matches that registered with the system.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Fixed or static data can't be larger than 64K

 Copy code hover
[image]

Fixed or static data can't be larger than 64K
Send feedback

Fixed and static data include nonautomatic variables, fixed-length strings, and fixed arrays. This error has the following causes and solutions:

  • You attempted to allocate more than 64K of module-level data.

    Reduce the amount of declared data. Note that although the size limit for module-level data is 64K, module-level variable-length strings and arrays can exceed this limit.

  • You attempted to allocate more than 64K of static procedure-level data in the module.

    Reduce the amount of this type of data declared. Static data from all procedures in a module is limited to a total of 64K (not 64K per procedure). Note that static variable-length strings and arrays can exceed this limit.

  • The size of a user-defined type exceeds 64K.

    Reduce the size of the user-defined type. Generally the size of a user-defined type equals the sum of the sizes specified for its elements. On some platforms there may be padding between the elements to keep them aligned on word boundaries. If you nest one user-defined type in another, the size of the nested type must be included in the size of the new type.

  • In a procedure, you tried to declare a variable of user-defined type that requires more than 32K. Although the size limit of a variable of user-defined type is 64K at module level, variables of user-defined type in procedures can't exceed 32K. Reduce the size required for the user-defined type, or use a module-level variable.

  • The size of a fixed-length string declared within a procedure exceeds 65,464. Reduce the length of the fixed-length string. Note that variable-length strings can exceed this limit.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Fixed-length strings and use of the 'new' qualifier are not allowed for fields in a public user defined type defined in an object module

 Copy code hover
[image]

Fixed-length strings and use of the 'new' qualifier are not allowed for fields in a public user defined type defined in an object module
Send feedback

This error has the following cause and solution:

  • Fixed-length strings and the use of the 'new' qualifier are not allowed for fields in a public user defined type defined in an object module.


Fixed-length strings not allowed as the type of a public member of an object module; private object modules not allowed as the type of a public member of a public object module

 Copy code hover
[image]

Fixed-length strings not allowed as the type of a public member of an object module; private object modules not allowed as the type of a public member of a public object module
Send feedback

This error has the following cause and solution:

  • You cannot set the type of a public member of an object module to a fixed-length string. Use a different variable type.

  • You cannot set the type of a public member of a public object module to a private object module. Use a different type.


For control variable already in use

 Copy code hover
[image]

For control variable already in use
Send feedback

When you nest For...Next loops, you must use different control variables in each one. This error has the following cause and solution:

  • An inner For loop uses the same counter as an enclosing For loop. Check nested loops for repetition. For example, if the outer loop uses For Count = 1 To 25 , the inner loops can't use Count as the control variables.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


For Each can only iterate over a collection object or an array

 Copy code hover
[image]

For Each can only iterate over a collection object or an array
Send feedback

The For Each construct can only be used with collections and arrays. This error has the following cause and solution:

  • You specified an object that isn't a collection or array as the group part of the For Each syntax. Check the spelling of the item over which you want to iterate to make sure it corresponds to a collection or array in scope in this part of your code.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


For Each control variable must be Variant or Object

 Copy code hover
[image]

For Each control variable must be Variant or Object
Send feedback

A control variable is the element part of the For Each...Next statement syntax. This error has the following causes and solutions:

  • A collection has a control variable that isn't a Variant or Object type.

    Make sure the element part of the For Each...Next is a Variant or Object.

  • An array has a control variable that isn't a Variant.

    Make sure the element part of the For Each...Next is a Variant.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


For Each control variable on arrays must be Variant

 Copy code hover
[image]

For Each control variable on arrays must be Variant
Send feedback

A control variable is the element part of the For Each...Next statement syntax. This error has the following cause and solution:

  • An array has a control variable that isn't a Variant.

    Make sure the group part of the For Each...Next is a Variant type variable.

  • For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


For Each may not be used on array of user-defined type or fixed-length strings

 Copy code hover
[image]

For Each may not be used on array of user-defined type or fixed-length strings
Send feedback

For Each constructs are only valid for collections and arrays of intrinsic types, including arrays of objects. Also, arrays of fixed-length strings can't be iterated using For Each. This error has the following causes and solutions:

  • The elements of the array in your For Each construct have a user-defined type.

    Use an ordinary For...Next loop to iterate the elements of the array.

  • The elements of the array in your For Each construct have a fixed-length string type. Use an ordinary For...Next loop to iterate the elements of the array.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


For loop not initialized (Error 92)

 Copy code hover
[image]

For loop not initialized (Error 92)
Send feedback

For loop counters must be initialized. This error has the following cause and solution:

  • You jumped into the middle of a For...Next loop. Remove the jump into the loop. Placing labels inside a For...Next loop isn't recommended.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


For without Next

 Copy code hover
[image]

For without Next
Send feedback

Every For statement must have a matching Next statement. This error has the following cause and solution:

  • A For statement is used without a corresponding Next statement. Check for an incorrectly matched For...Next structure inside the outer For...Next structure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Form already displayed; can't show modally (Error 400)

 Copy code hover
[image]

Form already displayed; can't show modally (Error 400)
Send feedback

You can't use the Show method to display a visible form as modal. This error has the following cause and solution:

  • You tried to use Show, with the style argument set to 1 -vbModal, on an already visible form.

    Use either the Unload statement or the Hide method on the form before trying to show it as a modal form.


Form not found (Error 424)

 Copy code hover
[image]

Form not found (Error 424)
Send feedback

The form was not found. This error has the following cause and solution:

You tried to add a form to the UserForms collection using the Add method, but there is no form class of that name. For example, UserForms.Add "MyForm" , where , where MyForm doesn't exist.

Note Note

Make sure that the class name is available to your project.


Forward reference to user-defined type

 Copy code hover
[image]

Forward reference to user-defined type
Send feedback

A user-defined type must be defined before it can be referenced. This error has the following causes and solutions:

  • You declared a variable with a user-defined type before the definition of the user-defined type appears. In the following example, the variable OtherVar is declared before its type (OtherType ) is known:

    Copy code Copy code
    Type MyType
OtherVar As OtherType
End Type

Type OtherType
WholeVar As Integer
RealVar As Double
End Type

    Reposition the type definitions so that the forward reference doesn't occur.

  • You nested a user-defined type within itself.

    Copy code Copy code
    Type MyType
MyVar As Integer
OtherVar As MyType
End Type

    Remove the self-referencing nested type. This may occur indirectly if you nest a type within another type in which the first is already declared. Check the definition of each nested type to eliminate duplication.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Function call on left-hand side of assignment must return Variant or Object

 Copy code hover
[image]

Function call on left-hand side of assignment must return Variant or Object
Send feedback

A function call can appear on the left side of an assignment, but only if the return value of the function is an Object or Variant. This error has the following cause and solution:

  • The return type of the function on the left side of the assignment isn't a Variant or Object. Change the return type. Note that if the return value is an object or a Variant that contains an object, the assignment is to the default property of the object. If the Variant returned isn't an object, the assignment has no effect.

  • Everything in the call is correct, however, it can't be completed. For example, you may be trying to set a property that can only be set at design time. Enter design mode and set the property in the Property window. Remove the code that tried to set the property programmatically.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Function marked as restricted or uses a type not supported in Visual Basic

 Copy code hover
[image]

Function marked as restricted or uses a type not supported in Visual Basic
Send feedback

Not every procedure that appears in a type library or object library can be accessed by every programming language. The creator of a type or object library can designate some functions as restricted to prevent their use by macro languages. This error has the following causes and solutions:

  • You tried to use a function with a restricted specification. You can't use the function in your program. If you have documentation for the object represented by the library, check to see if a method is provided that gives equivalent functionality.

  • You tried to use a function that requires a parameter type or has a return type that isn't available in Visual Basic.

    Sometimes you can simulate return types with Visual Basic equivalents. Check the subtypes of the Variant data type . This may also work for non-Basic parameter types that are expected as references. However, you can't pass a Variant data type by value in an effort to simulate a non-Basic type.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Identifier too long

 Copy code hover
[image]

Identifier too long
Send feedback

Identifiers can't be more than 255 characters long. This error has the following cause and solution:

  • The identifier exceeds 255 characters. Reduce the length of the identifier.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Identifier under cursor isn't a procedure name

 Copy code hover
[image]

Identifier under cursor isn't a procedure name
Send feedback

You tried to view a procedure, but the identifier at the insertion point was not a procedure name. This error has the following cause and solution:

  • Identifier isn't a procedure name. Check the spelling of the identifier.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Illegal parameter. Can't write arrays (Error 328)

 Copy code hover
[image]

Illegal parameter. Can't write arrays (Error 328)
Send feedback

An illegal parameter was passed to the method. This error has the following cause and solution:

  • In the WriteProperties event of your User Control, you tried to do a PropBag.WriteProperty X, where X is an array. This isn't supported.

    You must write out each element of the array individually.


Illegal parameter. Can't write object because it does not support persistence.

 Copy code hover
[image]

Illegal parameter. Can't write object because it does not support persistence.
Send feedback

This error has the following causes and solutions:

  • You attempted to write an object to a PropertyBag object, but the object doesn't support one of the ActiveX persistence interfaces. To fix this, you must have access to the code for the object. It must a Visual Basic-created object and have its Persistable property set to True. Also, the Class must be either Public or Public Createable and be in an ActiveX Dll, ActiveX Exe, or UserControl project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Illegal parameter. Can't write user-defined type.

 Copy code hover
[image]

Illegal parameter. Can't write user-defined type.
Send feedback

This error has the following causes and solutions:

  • You've attempted to write a user-defined type to a PropertyBag object, which is not supported. To work around this, you can write each individual item of the user-defined type to the PropertyBag object.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Incorrect DLL version

 Copy code hover
[image]

Incorrect DLL version
Send feedback

Each version of Visual Basic works only with its corresponding dynamic-link library (DLL) (Windows) or code resource (Macintosh). This error has the following cause and solution:

  • Your version of the Visual Basic dynamic-link library or code resource doesn't match the version expected by this host application. The program is attempting to call routines in a DLL or code resource, but the version of the library or resource is inconsistent with either Visual Basic or the host application.

    Obtain the correct version of the library or resource, and make sure earlier versions don't precede the proper one on your path.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Incorrect OLE version

 Copy code hover
[image]

Incorrect OLE version
Send feedback

Your versions of the OLE dynamic-link libraries (DLL) (Windows) or code resource (Macintosh) don't match those expected by the host application. In Microsoft Windows, the application searches for the DLLs first in the current directory, then along your path settings, and then in the WINDOWS\SYSTEM directory. This error has the following cause and solution:

  • Earlier OLE DLLs were encountered in the search before the DLLs expected by the host application. You should not try to use both versions of the DLLs.

Note that on the Macintosh, OLE files are normally only found in the Extensions folder so it is unlikely that this error will occur.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Input past end of file (Error 62)

 Copy code hover
[image]

Input past end of file (Error 62)
Send feedback

You can't read past the end-of-file position. This error has the following cause and solution:

  • An Input # or Line Input # statement is reading from a file in which all data has been read or from an empty file. Use the EOF function immediately before the Input # statement to detect the end of file.

  • You used the EOF function with a file opened for Binary access. EOF only works with files opened for sequential Input access. Use Seek and Loc with files opened for Binary access.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Insufficient Immediate window memory to create variable

 Copy code hover
[image]

Insufficient Immediate window memory to create variable
Send feedback

Memory in the Immediate window is limited. This error has the following cause and solution:

  • You specified a variable in the Immediate window that must be instantiated, since it wasn't created in the program's code context.

    Delete the reference to the variable in the Immediate window, or declare the variable in the program's code context so that it doesn't have to be created in the Immediate window.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Insufficient memory to save Undo information

 Copy code hover
[image]

Insufficient memory to save Undo information
Send feedback

You won't be able to choose the Undo command to restore the current state after you perform this edit. This error has the following cause and solution:

  • The edit is too large to save for Undo. Try performing the edit in smaller increments.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Insufficient project information to load project on platform or with version now being used

 Copy code hover
[image]

Insufficient project information to load project on platform or with version now being used
Send feedback

When you save a project, extra information is saved to permit loading the project with a later version or on a different platform. This error has the following cause and solution:

  • When you saved this project, you received an error indicating that insufficient memory was available to save all the information that might be necessary to load the project with a different version or to load it on a different platform. Load the file using the Visual Basic version in which it was previously saved, or on the platform in which it was previously saved, and then save it again. If you don't receive any error messages during that save, you should be able to load it in the current version or on the current platform.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Interface not valid for Implements

 Copy code hover
[image]

Interface not valid for Implements
Send feedback

Not all interfaces can be implemented in Visual Basic. This error has the following cause and solution:

  • The interface contains some element that can't be supported by Visual Basic. For example, Visual Basic has no equivalent to the unsigned long integer type, Visual Basic can't designate a procedure parameter as "out-only." Although Visual Basic supports the use of the underscore character (_) in Visual Basic identifiers, it can't implement an interface that uses underscore characters in the names of its members.

    You can't implement the interface in Visual Basic.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Internal error (Error 51)

 Copy code hover
[image]

Internal error (Error 51)
Send feedback

Make sure this error wasn't generated by the Error statement or Raise method. This error has the following cause and solution:

  • An internal malfunction has occurred in Visual Basic. Unless this call was generated by the Error statement or Raise method, contact Microsoft Product Support Services to report the conditions under which the message appeared.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid Access mode

 Copy code hover
[image]

Invalid Access mode
Send feedback

In your Open statement, you specified a type of access that was invalid for the specified file type. This error has the following causes and solutions:

  • You attempted to open a file for Input, but specified an illegal access mode. You can omit the access mode specification when opening a file for input, but if you specify it, the access mode must be Read. Both Write and Read Write are invalid access modes on a file opened for Input.

  • You attempted to open a file for Append, but specified an invalid access mode. You can omit the access mode specification when opening a file for append, but if you specify it, the access mode must be Write. Both Read and Read Write are invalid access modes on a file opened for Append.

  • You attempted to open a file for Output, but specified an invalid access mode. You can omit the access mode specification when opening a file for output, but if you specify it, the access mode must be Write. Both Read and Read Write are invalid access modes on a file opened for Output.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid attribute in Sub, Function, or Property

 Copy code hover
[image]

Invalid attribute in Sub, Function, or Property
Send feedback

Some attributes are invalid within procedures. This error has the following cause and solution:

  • A Public or Private attribute appears within the body of a procedure definition. Remove the attribute from the procedure. To give the variable wider scope, move the declaration to module level. Variables declared within procedures are always Private.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid Base Address

 Copy code hover
[image]

Invalid Base Address
Send feedback

You entered an invalid base address. This error has the following cause and solution:

  • On the Compile Tab in the Project Properties dialog, you specified an invalid Base Address. A valid base address must be a multiple of 64K, greater than 64K, and less than &H7FFF0000. This error occurs in ActiveX DLL or ActiveX Control projects.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid character

 Copy code hover
[image]

Invalid character
Send feedback

The character can't be used in the current context. This error has the following cause and solution:

  • You probably used an invalid character, such as a bracket or hyphen, as part of a variable name.

    Compare the spelling of the name with its declaration.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid Clipboard format (Error 460) [1 of 2]

 Copy code hover
[image]

Invalid Clipboard format (Error 460) [1 of 2]
Send feedback

The specified Clipboard format is incompatible with the method being executed. This error has the following causes and solutions:

  • You tried to use the GetText method or SetText method with a Clipboard format other than vbCFText or vbCFLink. Remove the invalid format and specify one of the two valid formats.

  • You tried to use the GetData or SetData method with a Clipboard format other than vbCFBitmap, vbCFDIB, or vbCFMetafile. Remove the invalid format and specify one of the three valid graphics formats.


Invalid Clipboard format (Error 460) [2 of 2]

 Copy code hover
[image]

Invalid Clipboard format (Error 460) [2 of 2]
Send feedback

The Clipboard only accepts data in certain specified formats. This error has the following cause and solution:

  • You tried to place data from a component on the Clipboard, but the data is in a format incompatible with the Clipboard. Consult the documentation for the component to determine whether you can use the Clipboard for transferring data from the component.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid data format

 Copy code hover
[image]

Invalid data format
Send feedback

The data read from a file wasn't in the expected format. This error has the following causes and solutions:

  • A project file or object library file is either corrupted or in a format that can't be understood.

    Get a new version of the project file or object library file.

  • You may have attempted to load an .exe file into a module.

    Load the source code instead.

  • You may have used the References dialog box and Object Browser to add a reference to a file that isn't a valid object library or contains a Basic project in a format not supported by the host application. For example, on the Windows platform, Microsoft Excel can't understand .bas or .frm files, or Microsoft Project files containing Basic code.

    Load the questionable file into the application in which it was created, and then save it in a compatible format. For example, object library source code can be processed through MkTypLib; and QuickBasic, and Visual Basic code can be saved in text format, and so on.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid data type for constant

 Copy code hover
[image]

Invalid data type for constant
Send feedback

Not all types of data can be assigned to constants. This error has the following cause and solution:

  • You tried to declare the type of a constant to be a user-defined type, an object, or an array.

    Remove the declaration or redeclare as a variable.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid event name

 Copy code hover
[image]

Invalid event name
Send feedback

Since an event procedure names are constructed by joining the object name to the event name with an underscore. This error has the following causes and solutions:

  • You used an underscore as part of the event name. Remove the underscore from the event name.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid file format (Error 321) [1 of 2]

 Copy code hover
[image]

Invalid file format (Error 321) [1 of 2]
Send feedback

A Visual Basic form file is damaged. This error has the following causes and solutions:

  • The form has a damaged ActiveX control.

    Try replacing the ActiveX control on the form.

  • The number of properties in the current version of the ActiveX control doesn't match the expected number of properties. Try replacing the ActiveX control with an earlier version or later version.


Invalid file format (Error 321) [2 of 2]

 Copy code hover
[image]

Invalid file format (Error 321) [2 of 2]
Send feedback

Disk files often have data stored in proprietary formats. This error has the following cause and solution:

  • You tried to load a file into a component, but the format of the data in the file was incompatible with the component. Consult the documentation for the component to determine the proper format for disk file data and whether the component provides support for converting from one format to another.

  • You tried to save component data to a file, but the format of the data was incompatible with the format of the file. Consult the documentation for the component to determine whether it provides support for converting from one format to another.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid format in resource file (Error 325)

 Copy code hover
[image]

Invalid format in resource file (Error 325)
Send feedback

When accessing a resource file, the resource you are trying to retrieve must have a valid format. This error has the following cause and solution:

  • The resource file you're trying to retrieve has an invalid format, or a specific resource in the file has an invalid format. If the file contents have been damaged, reinstall the file from its original disk. If the error continues, contact the provider of the resource for a new file or a version of the resource with the expected format.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid in Immediate window

 Copy code hover
[image]

Invalid in Immediate window
Send feedback

Not all statements are permitted in the Immediate window. This error has the following causes and solutions:

  • A declarative statement was used. For example, Const, Declare, Def type, Dim, Function, Option Base, Option Explicit, Option Compare, Option Private, Private, Public, property procedure declaration statements (Property Let, Property Set, and Property Get), ReDim, Static, Sub, and Type are not allowed in the Immediate window. Remove the declarative statements from the Immediate window.

  • A control flow statement was used, for example, Sub, Function, Property, GoSub, GoTo, Return, and Resume. Remove these statements from the Immediate window.

  • There is no logical connection made between separated physical lines in the Immediate window, so statements formatted as multiple physical lines, such as a block If statement, can't be properly executed. Such blocks can be typed on a single physical line, with each statement separated from the next by a colon (:). Conversely, you can extend a single statement across physical lines in the Immediate window by using the line-continuation character, which is a space followed by an underscore ( _).

  • You tried to execute some code in the Immediate window that invalidates the current state of your program and requires you to reinitialize the program. Remove the code in question from the Immediate window.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid inside Enum

 Copy code hover
[image]

Invalid inside Enum
Send feedback

Not all types are valid within an enumeration definition. This error has the following causes and solutions:

  • You tried to specify a string or some other invalid type as the value of an Enum member. The constant expression used to specify an Enum member must evaluate to type Long or another Enum type.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid inside procedure

 Copy code hover
[image]

Invalid inside procedure
Send feedback

The statement can't occur in a Sub or Function procedure. This error has the following cause and solution:

  • One of the following statements appears in a procedure: Declare, Def type, Private, Public, Option Base, Option Compare, Option Explicit, Option Private, Enum and Type.

    Remove the statement from the procedure. The statements can be placed at module level.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid length for fixed-length string

 Copy code hover
[image]

Invalid length for fixed-length string
Send feedback

This error has the following causes and solutions:

  • A fixed-length string is declared with zero length. A fixed-length string must have at least one character.

  • A fixed-length string exceeds the limit of 65,526.

    Reduce the length specified for the fixed-length string.

    Note Note

    Variable-length strings can exceed the upper limit and can have zero length.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid Next control variable reference

 Copy code hover
[image]

Invalid Next control variable reference
Send feedback

The numeric variable in the Next part of a For...Next loop must match the variable in the For part. This error has the following cause and solution:

  • The variable in the Next part of a For...Next loop differs from the variable in the For part. For example:

    Copy code Copy code
    For Counter = 1 To 10
MyVar = Counter
Next Count

    Check the spelling of the variable in the Next part to be sure it matches the For part. Also, be sure you haven't inadvertently deleted parts of the enclosing loop that used the variable.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid object use (Error 425)

 Copy code hover
[image]

Invalid object use (Error 425)
Send feedback

Most objects can only be used in specific ways, usually when trying to use an object outside the scope for which it is relevant. For example, an object reference passed into a drag-and-drop event can probably only be used in the context of that event.


Invalid optional parameter type

 Copy code hover
[image]

Invalid optional parameter type
Send feedback

Not all Visual Basic types are permitted for Optional parameters. This error has the following causes and solutions:

  • A parameter is defined with an invalid data type. For example, you can't have an Optional parameter of user-defined type. You may be able to accomplish your goal using an array of Variant type, since the elements of an array of Variant can store data of different types.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid or unqualified reference

 Copy code hover
[image]

Invalid or unqualified reference
Send feedback

An identifier beginning with a period is valid only within a With block. This error has the following cause and solution:

  • The identifier begins with a period. Complete the qualification of the identifier or remove the period.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid ordinal (Error 452)

 Copy code hover
[image]

Invalid ordinal (Error 452)
Send feedback

Your call to a dynamic-link library (DLL) indicated to use a number instead of a procedure name, using the #num syntax. This error has the following causes and solutions:

  • An attempt to convert the num expression to an ordinal failed. Make sure the expression represents a valid number or call the procedure by name.

  • The num specified doesn't specify any function in the DLL. Make sure num identifies a valid function in the DLL.

  • A type library has an invalid declaration resulting in internal use of an invalid ordinal number.

    Comment out code to isolate the procedure call causing the problem. Write a Declare statement for the procedure and report the problem to the type library vendor.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid outside Enum

 Copy code hover
[image]

Invalid outside Enum
Send feedback

An Enum is a data type that can be used to create groups of related constants (called enumerations). This error has the following causes and solutions:

  • You used an End Enum where it wasn't part of an Enum definition. Check for text that may appear between the body of the Enum definition and the End Enum statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid outside procedure

 Copy code hover
[image]

Invalid outside procedure
Send feedback

The statement must occur within a Sub or Function, or a property procedure (Property Get, Property Let, Property Set). This error has the following cause and solution:

  • An executable statement, Static or ReDim, appears at module level.

    Static is unnecessary at module level, since all module-level variables are static. Use Dim instead of ReDim at module level. To create a dynamic array at module level, declare it with Dim using empty parentheses.

    Note Note

    At module level, you can use only comments and declarative statements, such as Const, Declare, Def type, Dim, Option Base, Option Compare, Option Explicit, Option Private, Private, Public, and Type. The Sub, Function, and Property statements occur outside the body of their procedures, but within the procedure declaration.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid ParamArray use

 Copy code hover
[image]

Invalid ParamArray use
Send feedback

The parameter defined as ParamArray is used incorrectly in the procedure. This error has the following causes and solutions:

  • You attempted to pass ParamArray as an argument to another procedure that expects an array or a ByRef Variant.

    Assign the ParamArray parameter to a Variant, and then pass the variant.

  • You attempted to use an Erase or ReDim statement with a ParamArray parameter within its procedure. Remove the Erase or ReDim. These operations can't be performed on the ParamArray parameter.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid pattern string (Error 93)

 Copy code hover
[image]

Invalid pattern string (Error 93)
Send feedback

The pattern string specified in the Like operation of a search is invalid. This error has the following cause and solution:

  • A common example of an invalid character list expression is [a-b , where the right bracket is missing. Review the valid characters for list expressions.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid picture (Error 481) [1 of 2]

 Copy code hover
[image]

Invalid picture (Error 481) [1 of 2]
Send feedback

An invalid graphics format was assigned to the Picture property. This error has the following cause and solution:

  • You tried to assign a graphics format other than a bitmap, icon, or Windows metafile to the Picture property of a form or control. Ensure that the file you are trying to load into the Picture property is a valid graphics file supported by Visual Basic.


Invalid picture (Error 481) [2 of 2]

 Copy code hover
[image]

Invalid picture (Error 481) [2 of 2]
Send feedback

Only a picture can be assigned to the Picture property or Picture object. This error has the following cause and solution:

  • You attempted to assign something to a Picture property or a Picture object that isn't recognized as an icon, bitmap, or Microsoft Windows metafile. See the Help topics for the Picture object or Picture property of the object you're using to determine the acceptable picture types.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid picture type (Error 485)

 Copy code hover
[image]

Invalid picture type (Error 485)
Send feedback

The resource file picture format you tried to load doesn't match the specified property of the object. This error has the following causes and solutions:

  • You tried to use the LoadResPicture method to load a bitmap resource as the Icon property of a form. Change the property to the Picture property or change the format argument of LoadResPicture to vbResIcon.

  • You tried to use the LoadResPicture method to load a cursor resource as some property of an object or control other than the MousePointer property. Change the property reference to MousePointer.


Invalid procedure call or argument (Error 5)

 Copy code hover
[image]

Invalid procedure call or argument (Error 5)
Send feedback

Some part of the call can't be completed. This error has the following causes and solutions:

  • An argument probably exceeds the range of permitted values. For example, the Sin function can only accept values within a certain range. Positive arguments less than 2,147,483,648 are accepted, while 2,147,483,648 generates this error.

    Check the ranges permitted for arguments.

  • This error can also occur if an attempt is made to call a procedure that isn't valid on the current platform. For example, some procedures may only be valid for Microsoft Windows, or for the Macintosh, and so on.

    Check platform-specific information about the procedure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid procedure name

 Copy code hover
[image]

Invalid procedure name
Send feedback

There are restrictions in procedure-naming beyond the rules for naming identifiers. This error has the following cause and solution:

  • procedure host application

    Choose another name for the procedure.

  • Your procedure name is that of a restricted keyword, exceeds 255 characters, or doesn't begin with a letter. Choose a different name for the procedure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid property name

 Copy code hover
[image]

Invalid property name
Send feedback

This error has the following causes and solutions:

  • The name you entered for the property is invalid. That is, it is already in use, reserved for use by the system, or contains invalid characters.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid property value (Error 380) [1 of 2]

 Copy code hover
[image]

Invalid property value (Error 380) [1 of 2]
Send feedback

Most properties only accept values of a certain type, within a certain range. This error has the following cause and solution:

  • An inappropriate value has been assigned to a property. See the property's Help topic to determine what types and range of values are appropriate for the property.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid property value (Error 380) [2 of 2]

 Copy code hover
[image]

Invalid property value (Error 380) [2 of 2]
Send feedback

An inappropriate value is assigned to a property. This error has the following cause and solution:

  • You tried to set one of the properties of an object or control to a value outside its permissible range. Change the property value to a valid setting. For example, the MousePointer property must be set to an integer from 0 - 15 or 99.


Invalid property-array index (Error 381)

 Copy code hover
[image]

Invalid property-array index (Error 381)
Send feedback

A property value may consist of an array of values. This error has the following cause and solution:

  • A component's property array could have a lower bound of zero and an upper bound equal to the number of elements in the array minus 1. Alternatively, the lower bound could be 1 and the upper bound could equal the number of elements in the array. Check the component's documentation to make sure your index is within the valid range for the specified property.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid qualifier

 Copy code hover
[image]

Invalid qualifier
Send feedback

Qualifiers are used for disambiguation. This error has the following cause and solution:

  • The qualifier does not identify a project, module, object, or a variable of user-defined type within the current scope.

    Check the spelling of the qualifier. Make sure that the qualifying identifier is within the current scope. For example, a variable of user-defined type in a Private module is visible only within that module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid ReDim

 Copy code hover
[image]

Invalid ReDim
Send feedback

Not every array can be redimensioned. This error has the following causes and solutions:

  • A variable was implicitly declared a Variant, and you attempted to use ReDim to change it to an array.

    A Variant can contain an array, but if it isn't explicitly declared, you can't use ReDim to make it into an array. Declare the Variant before using ReDim to specify the number of elements it can contain. For example, in the following code, ReDim AVar(10) causes an invalid ReDim error, but ReDim BVar(10) does not:

    Copy code Copy code
    AVar = 1    ' Implicit declaration of AVar.
ReDim AVar(10)    ' Causes invalid ReDim error.
.
.
.
Dim BVar    ' Explicit declaration of BVar.
ReDim BVar(10)    ' No error.

  • You tried to use ReDim to change more than one dimension of an array contained within a Variant. You can only use ReDim to change the size of the last dimension of an array in a Variant. To create an array with multiple dimensions that can be redimensioned, the array can't be contained within a Variant, and you have to declare it the normal way.

  • You can use ReDim only to change the number of elements in a normal array, not the type of those elements. If you want an array in which you can change the types of the elements, use an array contained within a Variant. If you declare the array first, changing the types and the number of its elements can be accomplished as follows:

    Copy code Copy code
    Dim MyVar As Variant    ' Declare the variable.
ReDim MyVar(10) As String    ' ReDim it as array of String subtypes.
ReDim MyVar(20) As Integer    ' ReDim it as array of Integer subtypes.
ReDim MyVar(5) As Variant    ' ReDim it as array of Variant subtypes.

  • You attempted to use ReDim with an array that is a member of an Automation object.

    Remove the ReDim.

    Note Note

    If you don't specify a type for a variable, the variable receives the default type, Variant. This isn't always obvious. For example, the following code declares two variables, the first, MyVar, is a Variant; the second, AnotherVar, is an Integer.

Copy code Copy code
Dim MyVar, AnotherVar As Integer

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid syntax for conditional compiler constant declarations

 Copy code hover
[image]

Invalid syntax for conditional compiler constant declarations
Send feedback

Entering conditional compiler constants in an Options dialog box differs from declaring constants in code. This error has the following cause and solution:

  • You used improper syntax when entering a constant declaration in the in an Options dialog box. The only valid syntax is a simple assignment of an integer value to the identifier. Make sure the syntax for the entry is as follows, with each constant separated by a colon (:):

    Copy code Copy code
                              constantname
                          = [{+ | - }]integervalue : [{+ | - }]constantname = integervalue [...]

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid Template

 Copy code hover
[image]

Invalid Template
Send feedback

A derived class of a template can't be a template. This error has the following causes and solutions:

  • You tried to create an template component, but tried to derive it from a template. You can't derive a template class from a template.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid type-declaration character

 Copy code hover
[image]

Invalid type-declaration character
Send feedback

Type-declaration characters are valid, but don't exist for all data types; they aren't permitted in some situations. This error has the following causes and solutions:

  • A type-declaration character is appended to a variable declared in a Private, Public, or Static statement with an As clause.

    Remove the type-declaration character.

  • A type-declaration character is appended to an inconsistent literal. For example, since the ampersand (&) is the type-declaration character for a Long integer, appending it to a literal of a different type causes this error:

    Copy code Copy code
    10.253&

    Remove the type-declaration character or replace it with the correct one.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid use of AddressOf operator

 Copy code hover
[image]

Invalid use of AddressOf operator
Send feedback

The AddressOf operator modifies an argument to pass the address of a function rather than passing the result of the function call. This error has the following cause and solution:

  • You tried to use AddressOf with the name of a class method. Only the names of Visual Basic procedures in a .bas module can be modified with AddressOf. You can't specify a class method.

  • The procedure name modified by AddressOf is defined in a module in a different project.

  • You tried to modify the name a DLL function or a function defined in a type library with AddressOf.

  • DLL and type library functions can't be modified with AddressOf. The procedure definition must be in a module in the current project. Move the definition to a module in this project or include its current module in the project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid use of base class name

 Copy code hover
[image]

Invalid use of base class name
Send feedback

You cannot use the name of a base class by itself. This error has the following causes and solutions:

  • You tried to use the name of a base class by itself without making clear that you were trying to access the base class' default member. Place the base-class name within parentheses to indicate you want to access the default member.

  • You used the base-class name in an expression but the member you were trying to access was ambiguously specified. Use a disambiguator ( for example, an exclamation point) between the base-class name and the member you are interested in.

  • You used the base-class name in a Set statement as though it contained a reference to the class. Use the base-class name to retrieve a reference for example, using GetObject.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid use of Me keyword

 Copy code hover
[image]

Invalid use of Me keyword
Send feedback

The Me keyword can appear in class modules. This error has the following causes and solutions:

  • The Me keyword appeared in a standard module.

    The Me keyword can't appear in a standard module because a standard module doesn't represent an object. If you copied the code in question from a class module, you have to replace the Me keyword with the specific object or form name to preserve the original reference.

  • The Me keyword appeared on the left side of a Set assignment, for example:

    Copy code Copy code
    Set Me = MyObject    ' Causes "Invalid use of Me keyword" message.

    Remove the Set assignment.

    Note Note

    The Me keyword can appear on the left side of a Let assignment, in which case the default property of the object represented by Me is set. For example:

Copy code Copy code
Let Me = MyObject    ' Valid assignment with explicit Let.
Me = MyObject    ' Valid assignment with implicit Let.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid use of New keyword

 Copy code hover
[image]

Invalid use of New keyword
Send feedback

The New keyword can only be applied to a creatable object (an instance of a class or Automation object). This error has the following causes and solutions:

  • You tried to instantiate something that can have only one instance. For example, you tried to create a new instance of a module by specifying Module1 in a statement like the following:

    VBA Copy code Copy code
    Dim MyMod As New Module1

    You can't create the new instance, since a module can have only one instance.

  • You tried to instantiate an Automation object, but it was not a creatable object. For example, you tried to create a new instance of a list box by specifying ListBox in a statement like the following:

    VBA Copy code Copy code
    ' Valid syntax to create the variable.
Dim MyListBox As ListBox
Dim MyFormInst As Form
' Invalid syntax to instantiate the object.
Set MyFormInst = New Form
Set MyListBox = New ListBox

    ListBox and Form are class names, not specific object names. You can use them to specify that a variable will be a reference to a certain object type, as with the valid Dim statements above. But you can't use them to instantiate the objects themselves in a Set statement. You must specify a specific object, rather than the generic class name, in the Set statement:

    Copy code Copy code
    ' Valid syntax to create new instance of a form or list box.
Set MyFormInst = New Form1
Set MyListBox = New List1

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid use of Null (Error 94)

 Copy code hover
[image]

Invalid use of Null (Error 94)
Send feedback

Null is a Variant subtype used to indicate that a data item contains no valid data. This error has the following cause and solution:

  • You are trying to obtain the value of a Variant variable or an expression that is Null. For example:

    Copy code Copy code
    MyVar = Null
For Count = 1 To MyVar
. . .
Next Count

    Make sure the variable contains a valid value.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid use of object

 Copy code hover
[image]

Invalid use of object
Send feedback

You tried to use an object in an incorrect way. This error has the following causes and solutions:

  • You tried to discontinue an object reference by assigning Nothing to it but omitted the Set keyword:

    Copy code Copy code
    MyObject = Nothing

    Use the Set statement to set an object to Nothing. Assuming MyObject is an object, you must set it to Nothing with the Set statement:

    Copy code Copy code
    Set MyObject = Nothing

    Omitting the Set keyword is an implicit use of Let, which causes an attempt to perform a value assignment, rather than a reference assignment. Nothing can't be used in a value assignment.

  • You attempted to use Nothing in an expression.

    Rewrite the expression without the Nothing.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid watch expression

 Copy code hover
[image]

Invalid watch expression
Send feedback

The specified watch expression isn't a valid expression. This error has the following cause and solution:

  • The watch expression is syntactically incorrect. Check the syntax of all components in the expression. Note that the syntax for a watch expression corresponds to the locale of the project in which the expression being watched is defined.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Item' already exists in project

 Copy code hover
[image]

Item' already exists in project
Send feedback

The file you specified is already part of the project. You can't add the same file to a project more than once. You can't save a file with the same name as another file in the project.


'item' cannot be added because it is referenced but not in use by any items in the project. To correct this, uncheck 'Remove information about unused ActiveX Controls' in Project Options.

 Copy code hover
[image]

'item' cannot be added because it is referenced but not in use by any items in the project. To correct this, uncheck 'Remove information about unused ActiveX Controls' in Project Options.
Send feedback

This error has the following causes and solutions:

  • The indicated component cannot be added because it is not used by any items in the project. Clear the "Remove information about unused ActiveX Controls" in the Project Options dialog box under the Project menu.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Item' could not be loaded

 Copy code hover
[image]

Item' could not be loaded
Send feedback

Syntax errors are preventing Visual Basic from parsing and loading a file, or form name conflicts prevent loading of an ASCII form. The form won't be loaded and the form name won't be displayed in the Project Explorer.

Make sure that the file causing this error is a valid ASCII form in the correct format and that no conflicts exist among the different forms in the project.


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

 Copy code hover
[image]

'Item' could not be loaded. Remove it from the list of available add-ins?
Send feedback

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


Item' could not be registered

 Copy code hover
[image]

Item' could not be registered
Send feedback

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


'item' designers can only be used in DLL projects

 Copy code hover
[image]

'item' designers can only be used in DLL projects
Send feedback

This error has the following causes and solutions:

  • The indicated designer can be used only in ActiveX DLL projects. Try the designer in an ActiveX DLL project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


'item' designers cannot be private

 Copy code hover
[image]

'item' designers cannot be private
Send feedback

This error has the following causes and solutions:

  • The indicated designer's Instancing property cannot be set to Private.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


'item' designers cannot be public in ActiveX EXE projects

 Copy code hover
[image]

'item' designers cannot be public in ActiveX EXE projects
Send feedback

This error has the following causes and solutions:

  • The indicated designer's Instancing property cannot be set to Public in ActiveX .exe projects.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


'item' designers must be public and cannot be used in Standard EXE projects

 Copy code hover
[image]

'item' designers must be public and cannot be used in Standard EXE projects
Send feedback

This error has the following causes and solutions:

  • The indicated designer's Instancing property must be set to Public. The designer cannot be used in standard .exe projects.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


'Item' has an old file format. When saved, it will be saved in a newer format.

 Copy code hover
[image]

'Item' has an old file format. When saved, it will be saved in a newer format.
Send feedback

This file was created with an earlier version of Visual Basic. When you save it, it will be saved in the file format of the current version.


'item' has caused an access violation. Remove it from the list of available Add-Ins?

 Copy code hover
[image]

'item' has caused an access violation. Remove it from the list of available Add-Ins?
Send feedback

This error has the following causes and solutions:

  • The indicated add-in is causing a file access violation.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


'Item' is a binary form and can't be loaded into Visual Basic

 Copy code hover
[image]

'Item' is a binary form and can't be loaded into Visual Basic
Send feedback

Binary forms created with earlier versions of Visual Basic can't be loaded into this version of Visual Basic. Only Visual Basic versions 2.0 and 3.0 support converting binary forms to ASCII. If you have a copy of Visual Basic 2.0 or 3.0, you can load the form created with version 1.0 and those versions and save it as text. Then you can import the form in Visual Basic.


'Item' is a read-only file

 Copy code hover
[image]

'Item' is a read-only file
Send feedback

You asked to save to a file that is read-only. Read-only files are shown in the Project Explorer as [image]. You can't save to read-only files. Use Save As instead.


'item' is a single-threaded component and cannot be used in multi-threaded projects. Change the threading model for 'item' or contact the component vendor for an updated version.

 Copy code hover
[image]

'item' is a single-threaded component and cannot be used in multi-threaded projects. Change the threading model for 'item' or contact the component vendor for an updated version.
Send feedback

This error has the following causes and solutions:

  • You're attempting to use a single-threaded component in an multi-threaded project. You can change the threading model for the single-threaded component, or contact the component's vendor for an updated version.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


'Item' property can't be read at run time (Error 393)

 Copy code hover
[image]

'Item' property can't be read at run time (Error 393)
Send feedback

The property is only available at design time. This error has the following cause and solution:

  • You tried to read a property at run time that is only accessible at design time.

    Change your code and remove the reference to the property.


'Item' property can't be set at run time (Error 382)

 Copy code hover
[image]

'Item' property can't be set at run time (Error 382)
Send feedback

The property is read-only at run time. This error has the following cause and solution:

  • You tried to set or change a property whose value can only be set at design time.

    Remove the reference to the property from your code or change the reference to only return the value of the property at run time.


'Item' property is read-only (Error 383)

 Copy code hover
[image]

'Item' property is read-only (Error 383)
Send feedback

The property is read-only at both design time and run time. This error has the following cause and solution:

  • You tried to set or change a property whose value can only be read. Remove the reference to the property from your code or change the reference to only return the value of the property at run time.


'Item' property is write-only (Error 394)

 Copy code hover
[image]

'Item' property is write-only (Error 394)
Send feedback

The property can't be read. This error has the following cause and solution.

  • A property can't be read; for example, ctl.property = 3 might be legal, but "Printctl.property " would generate this error. Change your code and remove the reference to the property.


'Item' will not be loaded. Name is already in use

 Copy code hover
[image]

'Item' will not be loaded. Name is already in use
Send feedback

You can't have two items of the specified kind loaded at the same time.


'item1' is an invalid key. The file 'item2' can't be loaded

 Copy code hover
[image]

'item1' is an invalid key. The file 'item2' can't be loaded
Send feedback

You can't load the file while it contains the invalid key.


'item1' is referenced by 'item2' project and cannot be updated.

 Copy code hover
[image]

'item1' is referenced by 'item2' project and cannot be updated.
Send feedback

The specified control is referenced by more than one project. Updating it for one project might invalidate it for another.


Label not defined

 Copy code hover
[image]

Label not defined
Send feedback

This error has the following cause and solution:

  • A line label or line number is referred to (for example in a GoTo statement), but doesn't occur within the scope of the reference.

    The label must be within the procedure that contains the reference. Line labels are visible only in their own procedures.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Language/region setting has changed

 Copy code hover
[image]

Language/region setting has changed
Send feedback

This error has the following cause and solution:

  • You changed the default language/region setting for the Visual Basic environment. Be aware that this may cause problems, although by itself it is legal.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


License information for this component not found. You don't have an appropriate license to use this functionality in the design environment (Error 429)

 Copy code hover
[image]

License information for this component not found. You don't have an appropriate license to use this functionality in the design environment (Error 429)
Send feedback

You are not a licensed user of the ActiveX control. This error has the following cause and solution:

  • You tried to place an ActiveX control on a form at design time or tried to add a form with an ActiveX control on it to a project, but the associated information in the registry could not be found.

    The information in the registry may have been deleted or become corrupted. Reinstall the ActiveX control or contact the control vendor.


Line isn't an executable statement

 Copy code hover
[image]

Line isn't an executable statement
Send feedback

Declarations and comments are not executable statements. This error has the following cause and solution:

  • You chose the Step To Cursor command, but the cursor was not on a line containing an executable statement. Place the cursor on an executable statement near the current line.

For additional information, choose the Step To Cursor command on the Run menu and press F1 (in Windows) or HELP (on the Macintosh).


Line 'item1': All controls must precede menus; can't load control 'item2'.

 Copy code hover
[image]

Line 'item1': All controls must precede menus; can't load control 'item2'.
Send feedback

A control appeared in an incorrect location in the ASCII form file. All controls must be loaded before menus.


Line 'item1': Can't create embedded object in 'item2'

 Copy code hover
[image]

Line 'item1': Can't create embedded object in 'item2'
Send feedback

An embedded object could not be created while loading a form, User Control, User Document, or Property Page from a text file. For example, you would get this error if you previously inserted a Microsoft Word document onto the form, and then removed Microsoft Word from your system. This message is written to the error log file.


Line 'item1': Can't create embedded object in 'item2'; license not found

 Copy code hover
[image]

Line 'item1': Can't create embedded object in 'item2'; license not found
Send feedback

An embedded object could not be created during the load of a form, User Control, User Document, or Property Page from a text file, due to the license file not being found. You must have a license to use this object. Check with the object's vendor for more information. This message is written to the error log file.


Line 'item1': Can't load control 'item2'; containing control not a valid container.

 Copy code hover
[image]

Line 'item1': Can't load control 'item2'; containing control not a valid container.
Send feedback

You attempted to load a control into a control which isn't a valid container.


Line 'item1': Can't load control 'item2'; license not found

 Copy code hover
[image]

Line 'item1': Can't load control 'item2'; license not found
Send feedback

An ActiveX control could not be created while loading a form, User Control, User Document, or Property Page from a text file. The control may be missing or corrupted. Reinstall the control and try again. This message is written to the error log file.


Line 'item1': Can't load control 'item2'; name already in use.

 Copy code hover
[image]

Line 'item1': Can't load control 'item2'; name already in use.
Send feedback

The control named in the ASCII text file couldn't be loaded because its name is already in use in the application.


Line 'item1': Can't set checked property in menu 'item2'. Parent menu can't be checked.

 Copy code hover
[image]

Line 'item1': Can't set checked property in menu 'item2'. Parent menu can't be checked.
Send feedback

A top-level Menu control appeared in the ASCII form file with its Checked property set to True. Top-level menus can't be checked. The Menu control will be loaded, but its Checked property won't be set.


Line 'item1': Can't set Shortcut property in menu 'item2'. Parent menu cannot have a shortcut key.

 Copy code hover
[image]

Line 'item1': Can't set Shortcut property in menu 'item2'. Parent menu cannot have a shortcut key.
Send feedback

A top-level Menu control appeared in the ASCII form file with a shortcut key defined. Top-level menus can't have a shortcut key. The Menu control will be loaded, but its Shortcut property won't be set.


Line 'item1': Class 'item2' of control 'item3' was not a loaded control class.

 Copy code hover
[image]

Line 'item1': Class 'item2' of control 'item3' was not a loaded control class.
Send feedback

The ASCII file contains a control class that Visual Basic doesn't recognize. Add the custom control with this class to your project.


Line 'item1': Class name too long; truncated to 'item2'.

 Copy code hover
[image]

Line 'item1': Class name too long; truncated to 'item2'.
Send feedback

The ASCII file contains a class name longer than 40 characters. The class will be loaded with the name truncated to 40 characters.


Line 'item1': Control name too long; truncated to 'item2'.

 Copy code hover
[image]

Line 'item1': Control name too long; truncated to 'item2'.
Send feedback

The ASCII file contains a control name longer than 40 characters. The control will be loaded with the name truncated to 40 characters.


Line 'item1': Could not create reference: 'item2'

 Copy code hover
[image]

Line 'item1': Could not create reference: 'item2'
Send feedback

The reference indicated at the specified line could not be created.


Line 'item1': Did not find an index property, and control 'item2' already exists.

 Copy code hover
[image]

Line 'item1': Did not find an index property, and control 'item2' already exists.
Send feedback

The control can't be loaded because there is no index, and it has the same name as a previously loaded control.


Line 'item1': 'item2' has a quoted string where the property name should be.

 Copy code hover
[image]

Line 'item1': 'item2' has a quoted string where the property name should be.
Send feedback

A quoted string appeared in the ASCII form file where the property name was expected. Property names are not placed inside quotation marks (" ").


Line 'item1': Maximum nesting level for controls exceeded with 'item2'.

 Copy code hover
[image]

Line 'item1': Maximum nesting level for controls exceeded with 'item2'.
Send feedback

The ASCII file contains controls nested more than 7 levels deep.


Line 'item1': Missing or invalid control class in file 'item2 '.

 Copy code hover
[image]

Line 'item1': Missing or invalid control class in file 'item2 '.
Send feedback

The ASCII file contains an unknown control class in the form description, or the class name isn't a valid string in Visual Basic.


Line 'item1': Missing or invalid control name in file 'item2'.

 Copy code hover
[image]

Line 'item1': Missing or invalid control name in file 'item2'.
Send feedback

The ASCII file contains an unknown control name in the form description, or the control name isn't a valid string in Visual Basic.


Line 'item1': Parent menu 'item2' can't be loaded as a separator.

 Copy code hover
[image]

Line 'item1': Parent menu 'item2' can't be loaded as a separator.
Send feedback

The ASCII file contains a Menu control whose parent or top-level menu is defined as a menu separator. Top-level menus can't be menu separators. The separator won't be set.


Line 'item1': Property 'item2' in control 'item3' had an invalid property index.

 Copy code hover
[image]

Line 'item1': Property 'item2' in control 'item3' had an invalid property index.
Send feedback

The ASCII file contains a property name with a property index greater than 255.


Line 'item1': Property 'item2' in 'item3' could not be loaded.

 Copy code hover
[image]

Line 'item1': Property 'item2' in 'item3' could not be loaded.
Send feedback

The ASCII file contains an unknown property. The property will be skipped when loading the form.


Line 'item1': Property 'item2' in 'item3' could not be set.

 Copy code hover
[image]

Line 'item1': Property 'item2' in 'item3' could not be set.
Send feedback

Visual Basic can't set the property of the specified control as indicated by the form description in the ASCII file.


Line 'item1': Property 'item2' in 'item3' had an invalid file reference.

 Copy code hover
[image]

Line 'item1': Property 'item2' in 'item3' had an invalid file reference.
Send feedback

The ASCII file contains a reference to a file that Visual Basic couldn't find in the specified directory.


Line 'item1': Property 'item2' in 'item3' had an invalid value.

 Copy code hover
[image]

Line 'item1': Property 'item2' in 'item3' had an invalid value.
Send feedback

The ASCII file contains a property with a value that isn't correct for this control. The property is set with its default value.


Line 'item1': Property 'item2' in 'item3' must be a quoted string.

 Copy code hover
[image]

Line 'item1': Property 'item2' in 'item3' must be a quoted string.
Send feedback

The ASCII file contains a property that should appear inside quotation marks (" "), but the quotation marks are missing. This line in the form description is ignored.


Line 'item1': Syntax error: property 'item2' in 'item3' was missing an equal sign (=).

 Copy code hover
[image]

Line 'item1': Syntax error: property 'item2' in 'item3' was missing an equal sign (=).
Send feedback

The ASCII file contains a property name and value without an equal sign (=) between them. The property isn't loaded.


Line 'item1': The CLSID 'item2' for 'item3' is invalid.

 Copy code hover
[image]

Line 'item1': The CLSID 'item2' for 'item3' is invalid.
Send feedback

An object could not be loaded while loading a Form, User Control, User Document, or Property Page from a text file. The CLSID specified in the file is not valid. Applies only to objects that are properties, such as the Font object. This message is written to the error log file.


Line 'item1': The control name 'item2' is invalid.

 Copy code hover
[image]

Line 'item1': The control name 'item2' is invalid.
Send feedback

The ASCII file contains a control name that isn't a valid string in Visual Basic. The control isn't loaded.


Line 'item1': The file 'item2' could not be loaded.

 Copy code hover
[image]

Line 'item1': The file 'item2' could not be loaded.
Send feedback

Syntax errors are preventing Visual Basic from parsing and loading a file, or form name conflicts prevent loading of an ASCII form. The form won't be loaded and the form name won't be displayed in the Project Explorer.

Make sure that the file causing this error is a valid ASCII form in the correct format and that no conflicts exist among the different forms in the project.


Line 'item1': The Form or MDIForm name 'item2' is already in use; can't load this form.

 Copy code hover
[image]

Line 'item1': The Form or MDIForm name 'item2' is already in use; can't load this form.
Send feedback

The ASCII file contains a form with a name that is already being used in the application. The form isn't loaded.


Line 'item1': The Form or MDIForm name 'item2' is not valid; can't load this form.

 Copy code hover
[image]

Line 'item1': The Form or MDIForm name 'item2' is not valid; can't load this form.
Send feedback

The ASCII file contains a form name that isn't a valid string in Visual Basic. The form isn't loaded.


Line 'item1': The property name 'item2' in 'item3' is invalid.

 Copy code hover
[image]

Line 'item1': The property name 'item2' in 'item3' is invalid.
Send feedback

The ASCII file contains a property name that isn't a valid property for that control.


Line too long

 Copy code hover
[image]

Line too long
Send feedback

A physical line of Visual Basic code can contain up to 1023 characters. This error has the following cause and solution:

  • A line contains too many characters. You can create a longer logical line by joining physical lines with a line-continuation character, a space followed by an underscore ( _). Up to 25 physical lines can be joined with line-continuation characters to form a single logical line, or 24 consecutive line-continuation characters. Thus, a logical line could potentially contain a total of 10,230 characters. Beyond that, you must break the line into individual statements or assign some expressions to intermediate variables.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Loop without Do

 Copy code hover
[image]

Loop without Do
Send feedback

A Do loop must begin with a Do statement. This error has the following cause and solution:

  • You have an unterminated loop block nested within another loop. Check to verify that the correct Do...Loop syntax is used.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


LSet allowed only on strings and user-defined types

 Copy code hover
[image]

LSet allowed only on strings and user-defined types
Send feedback

LSet is used to left align data within strings and variables of user-defined type. This error has the following causes and solutions:

  • The specified variable isn't a string or user-defined type. If you are trying to block assign one array to another, LSet does not work. You must use a loop to assign each element individually.

  • You tried to use LSet with an object. LSet can also be used to assign the elements of a user-defined type variable to the elements of a different, but compatible, user-defined type. Although objects are similar to user-defined types, you can't use LSet on them. Similarly, you can't use LSet on variables of user-defined types that contain strings, objects, or variants.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


LSet not allowed

 Copy code hover
[image]

LSet not allowed
Send feedback

LSet is used to left-align data within strings and variables of user-defined type. This error has the following cause and solution:

  • You tried to use LSet on a user-defined type containing strings, objects, or variants. You must assign the elements individually from this variable of user-defined type to another.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Maximum number of watch expressions added

 Copy code hover
[image]

Maximum number of watch expressions added
Send feedback

There is a limit to the number of watch expressions the Watch window can contain. This error has the following cause and solution:

  • You added the maximum number of watch expressions to the Watch window. Remove one watch expression for each new one you want to add, or display the value you want to know about in the Immediate window.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


MDI forms are not allowed in multithreaded projects. Any MDI form will be removed from this project. To keep the MDI form in the project select Cancel and change threading model to Thread Pool with only 1 thread.

 Copy code hover
[image]

MDI forms are not allowed in multithreaded projects. Any MDI form will be removed from this project. To keep the MDI form in the project select Cancel and change threading model to Thread Pool with only 1 thread.
Send feedback

This error has the following causes and solutions:

  • You've attempted to add an MDI form to a multi-threaded project. If you want to keep the MDI form in your project, change the the threading model to Thread Pool with only one thread.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Member identifier already exists in object module from which this object module derives

 Copy code hover
[image]

Member identifier already exists in object module from which this object module derives
Send feedback

Identifiers used for object module members can't conflict with names already used in an object module from which they derive. This error has the following cause and solution:

  • A procedure or data member identifier in your object module uses an identifier already used in the object module from which it derives. For example, a form has a BackColor property, so the following code would cause this error:

    VBA Copy code Copy code
    ' Form already has a BackColor property.
Dim BackColor As Integer    ' Generates the error.

Function BackColor()    ' Generates the error.
End Function

    Change the identifier that conflicts with the member identifier in your object module.

    Note Note

    The following names cannot be used as property or method names because they belong to the underlying IUnknown and IDispatch interfaces: QueryInterface, AddRef, Release, GetTypeInfoCount, GetTypeInfo, GetIDsOfNames, Invoke. Using these names causes a compilation error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Method not valid without suitable object

 Copy code hover
[image]

Method not valid without suitable object
Send feedback

Not all methods can be performed by all objects. This error has the following cause and solution:

  • You called a method without specifying an object, and the method isn't valid for the implicit object. For example, you can't use the Line method in a standard module without a valid object qualifier because a standard module can't display the output of the Line method.

    Explicitly qualify the method call with an object that can accept the method. For example, you can specify a form or picture box with the Line method.

    Note Note

    Other methods that need an explicit object qualifier when used in a standard module include Circle, Print, and PSet.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Method or data member not found (Error 461)

 Copy code hover
[image]

Method or data member not found (Error 461)
Send feedback

The collection, object, or user-defined type doesn't contain the referenced member. This error has the following causes and solutions:

  • You misspelled the object or member name. Check the spelling of the names and check the Type statement or the object documentation to determine what the members are and the proper spelling of the object or member names.

  • You specified a collection index that's out of range. Check the Count property to determine whether a collection member exists. Note that collection indexes begin at 1 rather than zero, so the Count property returns the highest possible index number.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Missing end bracket

 Copy code hover
[image]

Missing end bracket
Send feedback

Brackets in a statement must occur in matching pairs. This error has the following cause and solution:

  • An opening bracket isn't matched by a closing bracket. Place a closing bracket at the end of the material to be bracketed.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Module not found

 Copy code hover
[image]

Module not found
Send feedback

Modules aren't loaded from a code reference — they must be part of the project. This error has the following cause and solution:

  • The requested module doesn't exist in the specified project. For example, the statement MyModule.SomeVar = 5 generates this error when MyModule isn't visible in the project MyProject . See your host application documentation for information on including the module in the project.


Module too large

 Copy code hover
[image]

Module too large
Send feedback

A module contains code within the project. This error has the following cause and solution:

  • There is too much code in the module.

    Create a new module and move some of the procedures from this module to the new one. If the current module contains module-level declarations of data that must be visible to the procedures in the new module, declare that data as Public.

    Note Note

    Comments aren't counted as lines of code. Therefore, deleting comments doesn't prevent this error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Must be first statement on the line

 Copy code hover
[image]

Must be first statement on the line
Send feedback

Not all keywords can appear at the beginning of a line of code. This error has the following causes and solutions:

  • You preceded a Sub, Function, or Property statement with another statement on the same line. A Sub, Function, or Property statement must always be the first statement on any line in which it appears (unless preceded by the keyword Public, Private, or Static).

  • You preceded an End If, Else, or ElseIf statement with another statement on the same line. An End If, Else, or ElseIf (only when used in a block If structure) statement must always be the first statement on any line in which it appears.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Must close or hide topmost modal form first (Error 402)

 Copy code hover
[image]

Must close or hide topmost modal form first (Error 402)
Send feedback

The modal form you are trying to close or hide isn't on top of the z-order. This error has the following cause and solution:

  • Another modal form is higher in the z-order than the modal form you tried to close or hide. First use either the Unload statement or the Hide method on any modal form higher in the z-order. A modal form is a form displayed by the Show method, with the style argument set to 1 - vbModal.


Must specify which item(s) to print

 Copy code hover
[image]

Must specify which item(s) to print
Send feedback

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


Name conflicts with existing module, project, or object library

 Copy code hover
[image]

Name conflicts with existing module, project, or object library
Send feedback

Modules, object libraries, and referenced projects must be uniquely named within a project. This error has the following causes and solutions:

  • There is already a module, project, or object library with this name referenced in this project. A file name extension isn't considered part of the name, so different extensions can't be used to distinguish one file from another. Use a different name for one of the duplicate module, project, or object library references.

  • You attempted to add a reference to a project or object library whose file name (without an extension) is the same as the name of one of the current project's modules. Change either the module name or the name of the file that could not be added.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Name 'item' conflicts with existing module, project, or object library

 Copy code hover
[image]

Name 'item' conflicts with existing module, project, or object library
Send feedback

This error has the following causes:

  • You loaded a form, User Control, User Document, or Property Page that contains objects with conflicting names. This can occur if the file was edited outside of Visual Basic.

  • This error can occur when you rename a form to the same name as the project, another form, or a module. It can also occur when you rename the project to the same name as a form or module.


Named argument already specified

 Copy code hover
[image]

Named argument already specified
Send feedback

You can use a named argument only once in the argument list of each procedure invocation. This error has the following causes and solutions:

  • You specified the same named argument more than once in a single call. For example, if the procedure MySub expects the named arguments Arg1 and Arg2 , the following call would generate this error:

    Copy code Copy code
    Call MySub(Arg1 := 3, Arg1 := 5)

    Remove one of the duplicate specifications.

  • You specified the same argument both by position and with a named argument, for example:

    Copy code Copy code
    Call MySub(1, Arg1 := 3)

    Remove one of the duplicate specifications.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Named argument not found (Error 448)

 Copy code hover
[image]

Named argument not found (Error 448)
Send feedback

A named argument may not be used in a procedure invocation unless it appears in the procedure definition. This error has the following cause and solution:

  • You specified a named argument, but the procedure was not defined to accept an argument by that name. Check the spelling of the argument name.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Named arguments not allowed

 Copy code hover
[image]

Named arguments not allowed
Send feedback

Named arguments aren't permitted in all situations. This error has the following causes and solutions:

  • You tried to specify a named argument as an array index, for example:

    Copy code Copy code
    MyVar = MyArray(MyNamedArg := 1)

    Use an ordinary variable or constant expression as an array index.

  • You tried to specify a named argument with an object, for example:

    Copy code Copy code
    MyVar = MyObject(MyNamedArg := 1)

    Use a variable or constant expression if the object requires an argument. For example, if the default for an object is a method, the object's name represents the default method. If it needs arguments, specify them positionally.

  • You tried to specify a named argument with an external name:

    Copy code Copy code
    MyVar = [MyName](MyNamedArg := 1)

    Use an ordinary variable or constant expression if the external name needs an argument.

  • You tried to specify a named argument with a data member of an object, for example:

    Copy code Copy code
    MyVar = [MyObject].MyProperty(MyNamedArg := 1)

    Use an ordinary variable or constant expression if the data member needs an argument.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Need property-array index (Error 385)

 Copy code hover
[image]

Need property-array index (Error 385)
Send feedback

This property value consists of an array rather than a single value. This error has the following cause and solution:

  • You didn't specify the index for the property array you tried to access. Check the component's documentation to find the range for the indexes appropriate to the array. Specify an appropriate index in your property access statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Next without For

 Copy code hover
[image]

Next without For
Send feedback

A Next statement must have a preceding For statement that matches. This error has the following cause and solution:

  • A Next statement is used without a corresponding For statement. Check other control structures within the For...Next structure and verify that they are correctly matched. For example, an If without a matching End If inside the For...Next structure generates this error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


No creatable public component detected. Press F1 for more information.

 Copy code hover
[image]

No creatable public component detected. Press F1 for more information.
Send feedback

This error has the following causes and solutions:

  • Your project must have at least one public creatable component.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


No Help available

 Copy code hover
[image]

No Help available
Send feedback

Not all errors have an associated help topic. This error has the following causes and solutions:

  • You generated an error for which no Help exists. Check the Readme file. Help for late-breaking errors is often available through the Readme file.


No object (Error 31004)

 Copy code hover
[image]

No object (Error 31004)
Send feedback

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


No text selected

 Copy code hover
[image]

No text selected
Send feedback

You must select some text to perform this operation. This error has the following cause and solution:

  • You didn't select any text prior to initiating a Find or Replace operation. Some host applications permit you to specify selection scope when searching for and replacing text, even though no text is actually selected. To select text, place the pointer at the beginning of the desired selection, then hold down the SHIFT key and use either the arrow keys or click the end of the text to complete the selection. If you don't want to search selected text, undo the Selection option.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


No watch expression selected

 Copy code hover
[image]

No watch expression selected
Send feedback

You must have an expression selected when you choose the Instant Watch command. This error has the following cause and solution:

  • You didn't select an expression to watch before choosing Instant Watch. Highlight the watch expression in the Code window before choosing Instant Watch.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Not a legal object name: 'item

 Copy code hover
[image]

Not a legal object name: 'item
Send feedback

Form and control names must start with a letter and can be a maximum of 40 characters — including letters, numbers, and underscores (_).

Note that the Name property of a form or control is different from the Label properties — Caption, Text, and Value — that label or display the contents of a control at run time. These properties can be restricted keywords, can begin with a number, and can contain nonalphanumeric characters.


Not enough memory to completely save project

 Copy code hover
[image]

Not enough memory to completely save project
Send feedback

When a project is saved, extra information is usually saved to make it possible to load the project in a later version or on a different platform. This error has the following cause and solution:

  • Memory available is insufficient to save information that will be necessary if you attempt to load the project in a later version of Visual Basic or on a different platform. If you plan to open the project in a later version of Visual Basic or on another platform, close some applications and try to save again.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Not enough memory to load file

 Copy code hover
[image]

Not enough memory to load file
Send feedback

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


Not enough memory to run; quitting

 Copy code hover
[image]

Not enough memory to run; quitting
Send feedback

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


Object already loaded (Error 360)

 Copy code hover
[image]

Object already loaded (Error 360)
Send feedback

The control in the control array has already been loaded. This error has the following cause and solution:

  • You tried to add a control to a control array at run time with the Load statement but the index value you referred to already exists.

    Change the index reference to a new value or check whether your code is executing the same Load statement with the same index value reference more than once.


Object does not have a Property Let procedure

 Copy code hover
[image]

Object does not have a Property Let procedure
Send feedback

You can't assign a value to a property unless it has exposed a Property Let method. This error has the following causes and solutions:

  • You tried to assign a value to a property that hasn't exposed a Property Let method. You can't directly assign a value to this property. If you created the class, you can modify the interface by exposing a Property Let method. Otherwise, check the component's documentation to determine if there is an indirect method for assigning the value.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object does not source Automation events

 Copy code hover
[image]

Object does not source Automation events
Send feedback

An object must provide a default source interface so that you can write event procedures for its events. This error has the following causes and solutions:

  • You tried to write an event procedure for an event of an object, but that event isn't available outside the object. See your object's documentation for suggestions on less direct ways to deal with the event you are interested in.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object doesn't support current locale setting (Error 447)

 Copy code hover
[image]

Object doesn't support current locale setting (Error 447)
Send feedback

Not all objects support all locale settings. This error has the following causes and solutions:

  • You attempted to access an object that doesn't support the locale setting for the current project. For example, if your current project has the locale setting Canadian French, the object you are trying to access must support that locale setting.

    Check which locale settings the object supports.

  • The object relies on national language support in a dynamic-link library (DLL), for example, OLE2NLS.DLL, that may be out of date.

    Obtain a more recent version of the DLL, one that supports the current project locale.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object doesn't support named arguments (Error 446)

 Copy code hover
[image]

Object doesn't support named arguments (Error 446)
Send feedback

Not all objects support named arguments. This error has the following cause and solution:

  • You tried to access an object whose methods don't support named arguments.

    Specify arguments positionally when performing methods on this object. See the object's documentation for more information on argument positions and types.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object doesn't support this action (Error 445)

 Copy code hover
[image]

Object doesn't support this action (Error 445)
Send feedback

Not all objects support all actions. This error has the following cause and solution:

  • You referenced a method or property that isn't supported by this object.

    See the object's documentation for more information on the object and check the spellings of properties and methods.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object doesn't support this property or method (Error 438)

 Copy code hover
[image]

Object doesn't support this property or method (Error 438)
Send feedback

Not all objects support all properties and methods. This error has the following cause and solution:

  • You specified a method or property that doesn't exist for this Automation object.

    See the object's documentation for more information on the object and check the spellings of properties and methods.

  • You specified a Friend procedure to be called late bound. The name of a Friend procedure must be known at compile time. It can't appear in a late-bound call.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object library feature not supported

 Copy code hover
[image]

Object library feature not supported
Send feedback

It's possible to have features in an object library that have no equivalent in Visual Basic. This error has the following cause and solution:

  • An attempt was made to access an object library data type or function that can't be supported by Visual Basic.

    Contact the creator of the object library for more information on when it is appropriate to use the object library, and the tools with which it should be used.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object library for Visual Basic for Applications not found

 Copy code hover
[image]

Object library for Visual Basic for Applications not found
Send feedback

The Visual Basic for Applications object library is no longer a standalone file; it is integrated into the dynamic-link library (DLL).

Under unusual circumstances a previous version of the object library (vaxxx.olb or vaxxxx.olb) corresponding to the language of the project might be needed, but not found. This error has the following causes and solutions:

  • The object library is missing completely, isn't in the expected directory, or is an incorrect version. Search your disk to make sure the object library is in the correct directory, as specified in the host-application documentation.

If the missing library is a language version that is installed by the host application, it may be easiest to simply rerun the setup program. If a project requires a different language object library than the one that accompanies your host application (for example, if someone sends you a project written on a machine set up for a different language), make sure the correct language version of the Visual Basic object library is included with the project and it is installed in the expected location.

Applications may support different language versions of their object libraries. To find out which language version is required, display the References dialog box, and see which language is indicated at the bottom of the dialog box.

Object libraries exist in different versions for each platform. Therefore, when projects are moved across platforms, for example, from Macintosh to Microsoft Windows, the correct language version of the referenced library for that platform must be available in the location specified in your host application documentation. Note that some language codes are two characters while others are three characters.

The Visual Basic object library file name is constructed as follows:

  • Windows: Application Code + Language Code + [Version].OLB. For example: The French Visual Basic for Applications object library for version 2 was vafr2.olb.

  • Macintosh: Application Name Language Code [Version] OLB. For example: The French Visual Basic for Applications object library for version 2 was VA FR 2 OLB.

If you can't find a missing project or object library on your system, contact the referencing project's author. If the missing library is a Microsoft application object library, you can obtain it as follows:

  • If you have access to Microsoft electronic technical support services, refer to the technical support section of this Help file. Under electronic services, you will find instructions on how to use the appropriate service option.

  • If you don't have access to Microsoft electronic technical support services, Microsoft object libraries are available upon request as an application note from Microsoft. Information on how to contact your local Microsoft product support organization is also available in the technical support section of this Help file.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object library invalid or contains references to object definitions that could not be found

 Copy code hover
[image]

Object library invalid or contains references to object definitions that could not be found
Send feedback

This error has the following cause and solution:

  • An object library contains references to unfound object definitions or is otherwise invalid.


Object library not registered

 Copy code hover
[image]

Object library not registered
Send feedback

The Visual Basic for Applications object library is no longer a standalone file; it is integrated into the dynamic-link library (DLL).

In earlier versions, when you started an application that uses Visual Basic for Applications, certain object libraries were loaded. This error has the following cause and solution:

  • An attempt was made to load a previous version of the Visual Basic for Applications object library (vaxxx.olb) or host-application object libraries. However, the correct language version of these object libraries could not be found in the system registry.

    Reregister your application. On the Macintosh, delete the vba.ini file from the Macintosh Preferences folder, and restart your application.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object library's language setting incompatible with current project

 Copy code hover
[image]

Object library's language setting incompatible with current project
Send feedback

The reference couldn't be added. This error has the following cause and solution:

  • You attempted to add a reference to an object library whose locale isn't compatible with the locale of the current project. The reference was not added. To use that object library, a project whose locale is compatible with it must be created.

    Try registering both Visual Basic for Applications and the host application for the given language. The object library then becomes available in the References dialog box.

    Note Note

    When Visual Basic is the host application, it isn't possible to change a project's language setting. Any object libraries used must be compatible with the English/U.S. setting.


Object module must implement all procedures in interface

 Copy code hover
[image]

Object module must implement all procedures in interface
Send feedback

An interface is a collection of unimplemented procedure prototypes. This error has the following cause and solution:

  • You specified an interface in an Implements statement, but you didn't add code for all the procedures in the interface. You must write code for each of the procedures specified in the interface. An empty procedure is adequate; the procedure should implement the required behavior.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object required (Error 424)

 Copy code hover
[image]

Object required (Error 424)
Send feedback

References to properties and methods often require an explicit object qualifier. This error has the following causes and solutions:

  • You referred to an object property or method, but didn't provide a valid object qualifier. Specify an object qualifier if you didn't provide one. For example, although you can omit an object qualifier when referencing a form property from within the form's own module, you must explicitly specify the qualifier when referencing the property from a standard module.

  • You supplied an object qualifier, but it isn't recognized as an object. Check the spelling of the object qualifier and make sure the object is visible in the part of the program in which you are referencing it. In the case of Collection objects, check any occurrences of the Add method to be sure the syntax and spelling of all the elements are correct.

  • You supplied a valid object qualifier, but some other portion of the call contained an error. An incorrect path as an argument to a host application's File Open command could cause the error. Check arguments.

  • You didn't use the Set statement in assigning an object reference. If you assign the return value of a CreateObject call to a Variant variable, an error doesn't necessarily occur if the Set statement is omitted. In the following code example, an implicit instance of Microsoft Excel is created, and its default property (the string "Microsoft Excel") is returned and assigned to the Variant RetVal . A subsequent attempt to use RetVal as an object reference causes this error:

    Copy code Copy code
    Dim RetVal ' Implicitly a Variant.
' Default property is assigned to Type 8 Variant RetVal.
RetVal = CreateObject("Excel.Application")
RetVal.Visible = True ' Error occurs here.

    Use the Set statement when assigning an object reference.

  • In rare cases, this error occurs when you have a valid object but are attempting to perform an invalid action on the object. For example, you may receive this error if you try to assign a value to a read-only property. Check the object's documentation and make sure the action you are trying to perform is valid.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object server not found (Error 337)

 Copy code hover
[image]

Object server not found (Error 337)
Send feedback

The required .exe or .dll file can't be found.


Object variable not set (Error 91)

 Copy code hover
[image]

Object variable not set (Error 91)
Send feedback

There are two steps to creating an object variable. First you must declare the object variable. Then you must assign a valid reference to the object variable using the Set statement. Similarly, a With...End With block must be initialized by executing the With statement entry point. This error has the following causes and solutions:

  • You attempted to use an object variable that isn't yet referencing a valid object.

    Specify or respecify a reference for the object variable. For example, if the Set statement is omitted in the following code, an error would be generated on the reference to MyObject:

    VBA Copy code Copy code
    Dim MyObject As Object    ' Create object variable.
Set MyObject = Sheets(1)    ' Create valid object reference.
MyCount = MyObject.Count    ' Assign Count value to MyCount.

  • You attempted to use an object variable that has been set to Nothing.

    VBA Copy code Copy code
    Set MyObject = Nothing    ' Release the object.
MyCount = MyObject.Count    ' Make a reference to a released object.

    Respecify a reference for the object variable. For example, use a new Set statement to set a new reference to the object.

  • The object is a valid object, but it wasn't set because the object library in which it is described hasn't been selected in the Add References dialog box.

    Select the object library in the Add References dialog box.

  • The target of a GoTo statement is inside a With block.

    Don't jump into a With block. Make sure the block is initialized by executing the With statement entry point.

  • You specified a line inside a With block when you chose the Set Next Statement command.

    The With block must be initialized by executing the With statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object was unloaded (Error 364)

 Copy code hover
[image]

Object was unloaded (Error 364)
Send feedback

A form was unloaded from its own _Load procedure. This error has the following cause and solution:

  • A form with an Unload statement in its _Load procedure was implicitly loaded. For example, the following will implicitly load YourForm if it isn't already loaded:

    Copy code Copy code
    MyForm.BackColor = YourForm.BackColor.

    Remove the Unload statement from the Form_Load procedure.


One or more files in the project have changed. Do you want to save the changes now?

 Copy code hover
[image]

One or more files in the project have changed. Do you want to save the changes now?
Send feedback

One of the property settings or a code statement has changed for one or more of the files in the project, and the changes have not yet been saved. This is your last chance to save the changes before loading another project.


One or more instances of this object are running. Can't remove it at this time.

 Copy code hover
[image]

One or more instances of this object are running. Can't remove it at this time.
Send feedback

This error has the following causes and solutions:

  • You've attempted to remove an object that is currently running. Close all instances of the object before removing it from the project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


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

 Copy code hover
[image]

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

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


Only comments may appear after End Sub, End Function, or End Property

 Copy code hover
[image]

Only comments may appear after End Sub, End Function, or End Property
Send feedback

Only comments, directives, and declarations are permitted outside procedures. This error has the following cause and solution:

  • You placed executable code outside a procedure. Any nondeclarative lines outside a procedure must begin with a comment delimiter ('). Declarative statements must appear before the first procedure declaration. Comments are ignored when the code executes.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Only public user defined types defined in public object modules can be used as parameters or return types for public procedures of class modules or as fields of public user defined types

 Copy code hover
[image]

Only public user defined types defined in public object modules can be used as parameters or return types for public procedures of class modules or as fields of public user defined types
Send feedback

This error has the following cause and solution:

  • You attempted to use a public user defined type as a parameter or return type for a public procedure of a class module, or as a field of a public user defined type. Only public user defined types that are defined in a public object module can be used in this manner.


Only valid in object module

 Copy code hover
[image]

Only valid in object module
Send feedback

Some Visual Basic statements or constructs are valid only in object modules (forms, class modules, etc.). This error has the following causes and solutions:

  • You tried to use an invalid statement or construct (for example, the Implements statement, WithEvents keyword, or an event sink) in a non-class module. Place statements that generate this error in an object module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Operation not allowed in DLL

 Copy code hover
[image]

Operation not allowed in DLL
Send feedback

Not all Visual Basic statements are allowed within a dynamic-link library (DLL). This error has the following causes and solutions:

  • You tried to create a DLL from a class that contains a statement that can't be executed from a DLL.

    Check your class and remove any statements that can't be executed within a DLL, for example, the End statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Option Private Module not permitted in object module

 Copy code hover
[image]

Option Private Module not permitted in object module
Send feedback

Option Private Module makes the contents of a module unavailable to other projects, while preserving their availability to your project. This error has the following cause and solution:

  • The statement Option Private Module appears in an object module.

    Remove the Option Private Module statement from the module. Object modules have the characteristic of Option Private Module by default. Changing the default can't be done from code. See your host application's documentation for information on giving object module members wider visibility.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Optional argument must be Variant

 Copy code hover
[image]

Optional argument must be Variant
Send feedback

Optional arguments can have any intrinsic data type, but it must be a type with a single default value. This error has the following cause and solution:

  • You tried to specify Optional with a parameter that has no default value, for example, an array.

    Make sure any argument specified as Optional has a default value.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


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

 Copy code hover
[image]

Other applications are currently accessing an object in your program. Ending the program now could cause errors in those programs. End program at this time?
Send feedback

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


Out of memory (Error 31001)

 Copy code hover
[image]

Out of memory (Error 31001)
Send feedback

Your system could not allocate or access enough memory or disk space for the specified operation.


Out of memory (Error 7)

 Copy code hover
[image]

Out of memory (Error 7)
Send feedback

More memory was required than is available, or a 64K segment boundary was encountered. This error has the following causes and solutions:

  • You have too many applications, documents, or source files open. Close any unnecessary applications, documents, or source files that are open.

  • You have a module or procedure that's too large.

    Break large modules or procedures into smaller ones. This doesn't save memory, but it can prevent hitting 64K segment boundaries.

  • You are running Microsoft Windows in standard mode. Restart Microsoft Windows in enhanced mode.

  • You are running Microsoft Windows in enhanced mode, but have run out of virtual memory. Increase virtual memory by freeing some disk space, or at least ensure that some space is available.

  • You have terminate-and-stay-resident programs running. Eliminate terminate-and-stay-resident programs.

  • You have many device drivers loaded. Eliminate unnecessary device drivers.

  • You have run out of space for Public variables

    Reduce the number of Public variables.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Out of memory; some watches might have been deleted

 Copy code hover
[image]

Out of memory; some watches might have been deleted
Send feedback

When your system runs out of memory, watch expressions are deleted to make enough memory available to permit recovery from the condition. This error has the following cause and solution:

  • You have too many applications, projects, or modules loaded.

    To continue working, remove any dispensable elements from memory, including unnecessary applications, projects, or modules that may be loaded.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Out of resources

 Copy code hover
[image]

Out of resources
Send feedback

Certain types of resources called "handles" are used internally for many operations. This error has the following cause and solution:

  • Your code has reached a resource limit. Try saving, closing, and reloading your code. If you still receive this error message, reduce the number of objects referenced in the code.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Out of stack space (Error 28)

 Copy code hover
[image]

Out of stack space (Error 28)
Send feedback

The stack is a working area of memory that grows and shrinks dynamically with the demands of your executing program. This error has the following causes and solutions:

  • You have too many active Function, Sub, or Property procedure calls. Check that procedures aren't nested too deeply. This is especially true with recursive procedures, that is, procedures that call themselves. Make sure recursive procedures terminate properly. Use the Calls dialog box to view which procedures are active (on the stack).

  • Your local variables require more local variable space than is available.

    Try declaring some variables at the module level instead. You can also declare all variables in the procedure static by preceding the Property, Sub, or Function keyword with Static. Or you can use the Static statement to declare individual Static variables within procedures.

  • You have too many fixed-length strings. Fixed-length strings in a procedure are more quickly accessed, but use more stack space than variable-length strings, because the string data itself is placed on the stack. Try redefining some of your fixed-length strings as variable-length strings. When you declare variable-length strings in a procedure, only the string descriptor (not the data itself) is placed on the stack. You can also define the string at module level where it requires no stack space. Variables declared at module level are Public by default, so the string is visible to all procedures in the module.

  • You have too many nested DoEvents function calls. Use the Calls dialog box to view which procedures are active on the stack.

  • Your code triggered an event cascade. An event cascade is caused by triggering an event that calls an event procedure that's already on the stack. An event cascade is similar to an unterminated recursive procedure call, but it's less obvious, since the call is made by Visual Basic rather than by an explicit call in your code. Use the Calls dialog box to view which procedures are active (on the stack).

To display the Calls dialog box, select the Calls button to the right of the Procedure box in the Debug window or choose the Calls command. For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Out of string space (Error 14)

 Copy code hover
[image]

Out of string space (Error 14)
Send feedback

Visual Basic permits you to use very large strings. However, the requirements of other programs and the way you manipulate your strings may cause this error. This error has the following causes and solutions:

  • Expressions requiring that temporary strings be created for evaluation may cause this error. For example, the following code causes an Out of string space error on some operating systems:

    Copy code Copy code
    MyString = "Hello"
For Count = 1 To 100
MyString = MyString & MyString
Next Count

    Assign the string to a variable of another name.

  • Your system may have run out of memory, which prevented a string from being allocated. Remove any unnecessary applications from memory to create more space.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Overflow (Error 6)

 Copy code hover
[image]

Overflow (Error 6)
Send feedback

An overflow results when you try to make an assignment that exceeds the limitations of the target of the assignment. This error has the following causes and solutions:

  • The result of an assignment, calculation, or data type conversion is too large to be represented within the range of values allowed for that type of variable.

    Assign the value to a variable of a type that can hold a larger range of values.

  • An assignment to a property exceeds the maximum value the property can accept.

    Make sure your assignment fits the range for the property to which it is made.

  • You attempt to use a number in a calculation, and that number is coerced into an integer, but the result is larger than an integer. For example:

    Copy code Copy code
        Dim x As Long
    x = 2000 * 365   ' Error: Overflow

    To work around this situation, type the number, like this:

    Copy code Copy code
        Dim x As Long
    x = 2000 * 365   ' Error: Overflow
    Copy code Copy code
        Dim x As Long
    x = CLng(2000) * 365

    To work around this situation, type the number, like this:

    Copy code Copy code
        Dim x As Long
    x = CLng(2000) * 365

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


ParamArray must be declared as an array of Variant

 Copy code hover
[image]

ParamArray must be declared as an array of Variant
Send feedback

Each argument to a ParamArray parameter can be of a different data type. Therefore, the parameter itself must be declared as an array of Variant type. You can also supply any number of arguments to a ParamArray. When the call is made, each argument supplied in the call becomes a corresponding element of the Variant array. For example:

Copy code Copy code
Sub MySub(ParamArray VarArg())
    . . .
End Sub
Call MySub ("First arg", 2, 3.54)

This error has the following causes and solutions:

  • In the definition of the procedure, the ParamArray parameter is defined as an array of a type other than Variant.

    Redeclare the parameter type as an array of Variant elements.

  • No data type was specified for the ParamArray parameter, but the procedure definition is within the scope of a Def type statement, so the parameter is implicitly declared as having a type other than Variant. Use an explicit As Variant clause in the specification of the ParamArray parameter.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Path not found (Error 76)

 Copy code hover
[image]

Path not found (Error 76)
Send feedback

The path to a file includes the drive specification plus the directories and subdirectories that must be traversed to locate the file. A path can be relative or absolute. This error has the following cause and solution:

  • During a file-access or disk-access operation, for example, Open, MkDir, ChDir, or RmDir, the operating system was unable to find the specified path. Respecify the path.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Path/File access error (Error 75)

 Copy code hover
[image]

Path/File access error (Error 75)
Send feedback

During a file-access or disk-access operation, for example, Open, MkDir, ChDir, or RmDir, the operating system couldn't make a connection between the path and the file name. This error has the following causes and solutions:

  • The file specification isn't correctly formatted. A file name can contain a fully qualified (absolute) or relative path. A fully qualified path starts with the drive name (if the path is on another drive) and lists the explicit path from the root to the file. Any path that isn't fully qualified is relative to the current drive and directory.

  • You attempted to save a file that would replace an existing read-only file. Change the read-only attribute of the target file or save the file with a different file name.

  • You attempted to open a read-only file in sequential Output or Append mode. Open the file in Input mode or change the read-only attribute of the file.

  • You attempted to change a Visual Basic project within a database or document. You can't make design changes to the project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Permission denied (Error 70)

 Copy code hover
[image]

Permission denied (Error 70)
Send feedback

An attempt was made to write to a write-protected disk or to access a locked file. This error has the following causes and solutions:

  • You tried to open a write-protected file for sequential Output or Append. Open the file for Input or change the write-protection attribute of the file.

  • You tried to open a file on a disk that is write-protected for sequential Output or Append. Remove the write-protection device from the disk or open the file for Input.

  • You tried to write to a file that another process locked. Wait to open the file until the other process releases it.

  • You attempted to access the registry, but your user permissions don't include this type of registry access.

    On 32-bit Microsoft Windows systems, a user must have the correct permissions for access to the system registry. Change your permissions or have them changed by the system administrator.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Permission to use object denied (Error 419)

 Copy code hover
[image]

Permission to use object denied (Error 419)
Send feedback

You don't have the necessary permissions for the specified object. This error has the following cause and solution:

  • You don't currently have the authority to access this object. To change your permission assignments, see your system administrator or the object's creator.


Please see the Readme file for more information on this error

 Copy code hover
[image]

Please see the Readme file for more information on this error
Send feedback

Some topics were added to this product after Help was completed. Help explanations for these can be found in the host application's Readme file.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Printer driver does not support specified property (Error 483)

 Copy code hover
[image]

Printer driver does not support specified property (Error 483)
Send feedback

The printer driver for the printer in use doesn't support this property of the Printer object. This error has the following cause and solution:

  • The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer. Some property settings may have no effect, or several different property settings may all have the same effect. Settings outside the accepted range may or may not produce an error. For more information, see the manufacturer's documentation for the specific driver.


Printer error (Error 482) [1 of 2]

 Copy code hover
[image]

Printer error (Error 482) [1 of 2]
Send feedback

There is some problem that prevents printing. This error has the following causes and solutions:

  • You don't have a printer installed from the Windows Control Panel. Open the Control Panel, double-click the Printers icon, and click Add Printer to install a printer.

  • Your printer isn't online. Physically switch the printer online.

  • Your printer is jammed or out of paper. Physically correct the problem.

  • You tried to print a form to a printer that can accept only text. Switch to an installed printer that can print graphics.


Printer error (Error 482) [2 of 2]

 Copy code hover
[image]

Printer error (Error 482) [2 of 2]
Send feedback

This error has the following cause and solution:

  • An error occurred at the printer, but no other information was returned to the computer that sent the file. You must physically examine the printer. Make sure all connections between computer and printer are solid. Most printers provide a display for error information such as "Out of paper," "Offline," and so on.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Private Enum and user-defined types cannot be used as parameters or return types for public procedures, public data members, or fields of public user-defined types

 Copy code hover
[image]

Private Enum and user-defined types cannot be used as parameters or return types for public procedures, public data members, or fields of public user-defined types
Send feedback

A Public procedure is visible to all modules in a project, while a Private Enum type is not visible outside its own module. This error has the following cause and solution:

  • Your Public procedure is in a Public class, but it returns a value or has a parameter that is defined in a standard module or in a Private class.

    Declare the Enum Public. It must be in a class module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Private object modules cannot be used in public object modules as parameters or return types for public procedures, as public data members, or as fields of public user defined types

 Copy code hover
[image]

Private object modules cannot be used in public object modules as parameters or return types for public procedures, as public data members, or as fields of public user defined types
Send feedback

This error has the following cause and solution:

  • You attempted to use a private object module as a parameter in a public object module, or as a return type for a public procedure, data member, or as a field of a public user defined type, which is not allowed.


Problem getting printer information from the system; make sure the printer is set up correctly. (Error 484)

 Copy code hover
[image]

Problem getting printer information from the system; make sure the printer is set up correctly. (Error 484)
Send feedback

There is some problem that prevents getting printer information from the system. This error has the following causes and solutions:

  • You don't have a printer installed from the Windows Control Panel. Open the Control Panel, double-click the Printers icon, and click Add Printer to install a printer.

  • Your printer isn't online. Physically switch the printer online.

  • Your printer is jammed or out of paper. Physically correct the problem.


Procedure declaration does not match description of event or procedure having same name

 Copy code hover
[image]

Procedure declaration does not match description of event or procedure having same name
Send feedback

Your class module has a procedure name that conflicts with the name of an event. This error has the following cause and solution:

  • A procedure has the same name as an event, but does not have the same signature (that is, the number and types of the parameters). This can occur if you do something such as add a new parameter to an event procedure. For example, if you modify the definition of a form's Form_Load event procedure as follows, this error will occur:

    Copy code Copy code
    Sub Form_Load (MyParam As Integer)
. . .
End Sub

    If the procedure isn't the event procedure corresponding to the event, change its name. If the procedure corresponds to the event, make the parameter list agree with that required by the event (if any).

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Procedure too large

 Copy code hover
[image]

Procedure too large
Send feedback

When compiled, the code for a procedure can't exceed 64K. This error has the following cause and solution:

  • Code for this procedure exceeds 64K when compiled. Break this, and any other large procedures, into two or more smaller procedures.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Procedure type mismatch

 Copy code hover
[image]

Procedure type mismatch
Send feedback

You are using one kind of Property procedure where a different kind is expected. This error has the following causes and solutions:

  • You are trying to write to a property that is read-only.

    If the only property procedure defined for the property is a Property Get, you can't assign a value to the property. Either write an appropriate Property Let procedure, or don't attempt to write to the property.

  • You are trying to read a property that is write-only. If the only property procedure defined for the property is a Property Let, you can't read the value of the property. Either write an appropriate Property Get procedure, or don't attempt to write to the property.

  • You are trying to set a reference but the property has only Property Get or Property Let procedures. Either write a Property Set procedure for the property, or don't try to set a reference to it.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Programmatic ID string too long 'item'. The Programmatic ID must be 39 characters or less.

 Copy code hover
[image]

Programmatic ID string too long 'item'. The Programmatic ID must be 39 characters or less.
Send feedback

This error has the following causes and solutions:

  • The ProgID string of the ActiveX component can be no longer than 39 characters. The ProgID is created by concatenating the project name with the class module name.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Project

 Copy code hover
[image]

Project <name> has been modified. Do you wish to save the changes now?
Send feedback

This error has the following causes and solutions:

  • One of the property settings or a code statement has changed for one or more of the files in the project and the changes have not yet been saved. This is your last chance to save the changes before loading another project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Project contains too many procedure, variable, and constant names

 Copy code hover
[image]

Project contains too many procedure, variable, and constant names
Send feedback

A project's procedure, variable, constant, and parameter names are stored in a name table. This error has the following cause and solution:

  • The number of names in the project's name table exceeds 32,768. The name table may contain some temporary duplicates. You can compact the name table by saving the project to a disk, and then closing it. If the problem persists after you reopen the project, reduce the number of names by reusing local variable names in multiple procedures, and then recompact the table by saving the project, closing it, and reopening it.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Project file is read-only

 Copy code hover
[image]

Project file is read-only
Send feedback

The project file is not writable. To change it, you must save it under a different name or remove the read-only attribute.


Project is unviewable.

 Copy code hover
[image]

Project is unviewable.
Send feedback

This error has the following causes and solutions:

  • The project you are attempting to view is locked. Refer to documentation for the host application for Help on how to make the project viewable.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Project not found

 Copy code hover
[image]

Project not found
Send feedback

The project was not found. This error has the following cause and solution:

  • You specified a project name that can't be found. Check the way you specified the project for any errors.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property Get can't be executed at run time (Error 393)

 Copy code hover
[image]

Property Get can't be executed at run time (Error 393)
Send feedback

Not all properties return run-time information. This error has the following cause and solution:

  • The property you are trying to access is read-only at run time. Terminate execution and view the property in design time.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property Get can't be executed on write-only property (Error 394)

 Copy code hover
[image]

Property Get can't be executed on write-only property (Error 394)
Send feedback

Not all properties return information. This error has the following cause and solution:

  • The property you are trying to access doesn't return information. You can't determine the state of the property.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property let procedure not defined and property get procedure did not return an object (Error 451)

 Copy code hover
[image]

Property let procedure not defined and property get procedure did not return an object (Error 451)
Send feedback

Certain properties, methods, and operations can only apply to Collection objects. This error has the following cause and solution:

  • You specified an operation or property that is exclusive to collections, but the object isn't a collection.

    Check the spelling of the object or property name, or verify that the object is a Collection object. Also look at the Add method used to add the object to the collection to be sure the syntax is correct and that any identifiers were spelled correctly.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property not found (Error 422)

 Copy code hover
[image]

Property not found (Error 422)
Send feedback

Not all objects support the same set of properties. This error has the following cause and solution:

  • This object doesn't support the specified property. Check the spelling of the property name. Also, you may be trying to access something like a "text" property when the object actually supports a "caption" or some similarly named property. Check the object's documentation.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property or method not found (Error 423)

 Copy code hover
[image]

Property or method not found (Error 423)
Send feedback

The spelling of an object name must exactly match the definition in its object library. This error has the following cause and solution:

  • You referred to an object.method or object.property, but method or property isn't defined. You may have misspelled the name of the object. To see what properties and methods are defined for an object, display the Object Browser. Select the appropriate object library to view a list of available properties and methods.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property Set can't be executed at run time (Error 382)

 Copy code hover
[image]

Property Set can't be executed at run time (Error 382)
Send feedback

It may not be possible to obtain a reference to a property at run time.This error has the following cause and solution:

  • You tried to get a reference to a property that's either read-only or write-only at run time. Since you can use a reference for both reading and writing, the property must provide run-time support for both operations for a reference to be obtained at run time.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property Set can't be used with a read-only property (Error 383)

 Copy code hover
[image]

Property Set can't be used with a read-only property (Error 383)
Send feedback

It may not be possible to obtain a reference to a property at run time.This error has the following cause and solution:

  • You tried to get a reference to a property that's read-only at run time. Since you can use a reference for both reading and writing, the property must provide run-time support for both operations for a reference to be obtained at run time. You can only use a Property Get with this property.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property Set not permitted (Error 387)

 Copy code hover
[image]

Property Set not permitted (Error 387)
Send feedback

Not all properties support returning a reference. This error has the following cause and solution:

  • You tried to get a reference to a property that doesn't return a reference. Restrict your access to this property to Property Let and Property Get.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Qualified name disallowed in module scope

 Copy code hover
[image]

Qualified name disallowed in module scope
Send feedback

Under some circumstances, some host applications don't permit procedure calls that include qualified names. This error has the following cause and solution:

  • You specified a module name in a procedure call using dot notation (qualifier. item ).

    If you are receiving this error it is probably because the host application already knows the specified qualifier and doesn't need that information in the procedure call. In such a case, you can simply omit the qualifier altogether and the host application will make the procedure call correctly. Check the host application's documentation to find the reason for any other restrictions on qualified names.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Qualifier must be collection

 Copy code hover
[image]

Qualifier must be collection
Send feedback

The use of an exclamation point between two identifiers is specific to collections. This error has the following cause and solution:

  • You used a name on the left side of the exclamation point (!) that isn't the name of a collection. If the name is supposed to represent a collection, check to make sure the name is spelled correctly. Note that the exclamation point is also the type-declaration character for the Single data type. If the name in question isn't supposed to be a collection, perhaps the ! type-declaration character appended to a variable name has been concatenated with another name.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Range has no values

 Copy code hover
[image]

Range has no values
Send feedback

There are limitations on the way you can specify the number of elements in an array. This error has the following cause and solution:

  • You specified your array boundaries incorrectly. For example, the following ranges are invalid:

    Copy code Copy code
    Dim MyArray(10 To -5)    ' Descending order not permitted.
Dim MyArray(0 To 0)        ' No elements in the array.

    Check to be sure your syntax is correct. For example, the following range is valid:

    Copy code Copy code
    Dim MyArray(-5 To 10)

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Replacements too long (Error 746)

 Copy code hover
[image]

Replacements too long (Error 746)
Send feedback

A replacement may not exceed a specified maximum length. This error has the following cause and solution:

  • You specified a replacement that exceeded the length permitted. Consult the component documentation for maximum length restriction.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Requested type library or wizard is not a VBA project

 Copy code hover
[image]

Requested type library or wizard is not a VBA project
Send feedback

Not all elements available in Visual Basic are able to be both read from and written to. This error has the following causes and solutions:

  • You tried to write to an Addin or a type library from within a Visual Basic project. You can't directly write to a prepackaged Addin or a type library as part of a Visual Basic project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Resume without error (Error 20)

 Copy code hover
[image]

Resume without error (Error 20)
Send feedback

A Resume statement can only appear within an error handler and can only be executed in an active error handler. This error has the following causes and solutions:

  • You placed a Resume statement outside error-handling code. Move the statement into an error handler, or delete it.

  • Your code jumped into an error handler even though there was no error. Perhaps you misspelled a line label. Jumps to labels can't occur across procedures, so search the procedure for the label that identifies the error handler. If you find a duplicate label specified as the target of a GoTo statement that isn't an On Error GoTo statement, change the line label to agree with its intended target.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Return without GoSub (Error 3)

 Copy code hover
[image]

Return without GoSub (Error 3)
Send feedback

A Return statement must have a corresponding GoSub statement. This error has the following cause and solution:

  • You have a Return statement that can't be matched with a GoSub statement. Make sure your GoSub statement wasn't inadvertently deleted.

Unlike For...Next, While...Wend, and Sub...End Sub, which are matched at compile time, GoSub and Return are matched at run time.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


RSet allowed only on strings

 Copy code hover
[image]

RSet allowed only on strings
Send feedback

RSet is used to right align string data within fixed-length or variable-length strings. This error has the following cause and solution:

  • You tried to use the RSet statement on a variable that isn't a string.

    If appropriate, try converting the variable to a string. Otherwise, don't use RSet.

    Note Note

    Although the LSet statement can be used to assign the elements of one user-defined type variable to the elements of a different, but compatible, user-defined type, such assignments are discouraged because they can't be guaranteed to be portable.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Run-time error

 Copy code hover
[image]

Run-time error <number>:
Send feedback

This error is user-defined, and has the following cause and solution:

  • An error was generated that doesn't correspond to a Visual Basic error. Handle the error as indicated in the documentation for the object or object library that generated the error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Search string must be specified

 Copy code hover
[image]

Search string must be specified
Send feedback

You have to specify a search string. This error has the following cause and solution:

  • You tried to perform a search operation without a string for comparison. You must specify the search string. While you can specify a zero-length string ("") as a replacement string, a zero-length string has no meaning as a search string.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Search string must be specified (VBE)

 Copy code hover
[image]

Search string must be specified (VBE)
Send feedback

You have to enter a string when searching in the object browser. This error has the following causes and solutions:

  • You initiated a search in the Object Browser, but didn't specify text to search for. Enter a search string.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Search string too long or complex

 Copy code hover
[image]

Search string too long or complex
Send feedback

Visual Basic pattern-matching capabilities aren't unlimited. This error has the following cause and solution:

  • The search string specified is too long, or the combination of wildcard character specifications can't be understood. Reduce the length or complexity of the search string and retry the search.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Search text isn't found

 Copy code hover
[image]

Search text isn't found
Send feedback

No search text was found. This error has the following causes and solutions:

  • There is no matching text between the start point and end point of the specified search scope.

    You can widen the scope of the search if you want to continue searching.

  • You failed to provide a left bracket when using a pattern-matching expression.

    Provide the left bracket.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Search text not found (Error 744)

 Copy code hover
[image]

Search text not found (Error 744)
Send feedback

This error has the following cause and solution:

  • The text you specified wasn't found. The text doesn't exist.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Seek failed: can't read/write from the disk

 Copy code hover
[image]

Seek failed: can't read/write from the disk
Send feedback

Seek statements are carried out directly to disk. This error has the following causes and solutions:

  • You attempted to read from a disk or file that is write-protected, read-only, or locked. Remove the write-protected attribute or change the read-only attribute or lock. Note that if the file is locked by another process, you can't remove the lock.

  • The file has become unavailable, for example, if a removable disk has been physically changed. If the file has been moved to another disk, access it from there. Otherwise, you can't access the file.

  • You attempted to read from a project file, an object library, or a type library, but the file has been corrupted.

    Obtain a new copy of the library or project file.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Select Case without End Select

 Copy code hover
[image]

Select Case without End Select
Send feedback

Each Select Case construct must be terminated with an End Select statement. This error has the following cause and solution:

  • You used a Select Case statement without a corresponding End Select statement. Check if there is an incorrectly matched Select Case...End Select structure inside an outer Select Case...End Select structure. If you have nested Select Case statements, each must have a matching End Select.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Selected watch expression invalid

 Copy code hover
[image]

Selected watch expression invalid
Send feedback

It isn't always possible to select a valid watch expression. This error has the following causes and solutions:

  • You chose the Instant Watch command, but the selected expression isn't a valid expression. For example, you can't watch a comment or a Sub procedure call.

    Select the expression in such a way that it is valid, or choose Add Watch and type in a valid expression.

  • The watch expression must have code syntax corresponding to the locale of the project that defines the expression being watched.

    Rewrite the expression in a way that is valid for the locale.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Set Next Statement can only apply to executable lines within current procedure.

 Copy code hover
[image]

Set Next Statement can only apply to executable lines within current procedure.
Send feedback

You can choose the Set Next Statement command to indicate where a suspended program should begin when execution is continued. This error has the following causes and solutions:

  • When you chose the command, the cursor was on a line that didn't contain an executable statement. Place the cursor on a line with an executable statement and try again. Declarations, line labels, and comments aren't executable, so lines with only declarations, labels, and comments can't be the targets of the Set Next Statement command.

  • When you chose the command, the cursor was on a line outside the currently executing procedure.

    Place the cursor on a line within the currently executing procedure.


SHARE.EXE required

 Copy code hover
[image]

SHARE.EXE required
Send feedback

The program share.exe must be running when you start Visual Basic. This error has the following cause and solution:

  • You didn't start share.exe before starting Visual Basic. Close your application, start share.exe, then restart your application. To avoid this problem in the future, place an invocation of share.exe in your autoexec.bat file so share.exe automatically starts when you turn on your machine.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Specified ActiveX component not correctly registered or not found

 Copy code hover
[image]

Specified ActiveX component not correctly registered or not found
Send feedback

A component should be registered in the system registry. This error has the following cause and solution:

  • The component's registry information is incorrect, so the component can't be found. Correct the registry. Reinstall the component, if necessary.

  • The component was removed by deleting it instead of using an uninstall program. Replace the component files in the directory specified in the registry.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Specified DLL function not found (Error 453)

 Copy code hover
[image]

Specified DLL function not found (Error 453)
Send feedback

The dynamic-link library (DLL) in a user library reference was found, but the DLL function specified wasn't found within the DLL. This error has the following causes and solutions:

  • You specified an invalid ordinal in the function declaration. Check for the proper ordinal or call the function by name.

  • You gave the right DLL name, but it isn't the version that contains the specified function. You may have the correct version on your machine, but if the directory containing the wrong version precedes the directory containing the correct one in your path, the wrong DLL is accessed. Check your machine for different versions. If you have an early version, contact the supplier for a later version.

  • If you are working on a 32-bit Microsoft Windows platform, both the DLL name and alias (if used) must be correct. Make sure the DLL name and alias are correct.

  • Some 32-bit DLLs contain functions with slightly different versions to accommodate both Unicode and ANSI strings. An "A" at the end of the function name specifies the ANSI version. A "W" at the end of the function name specifies the Unicode version.

    If the function takes string-type arguments, try appending an "A" to the function name.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Specified format doesn't match format of data (Error 461)

 Copy code hover
[image]

Specified format doesn't match format of data (Error 461)
Send feedback

The specified Clipboard format is incompatible with the method being executed. This error has the following causes and solutions:

  • You tried to use the GetText method or SetText method with a Clipboard format other than vbCFText or vbCFLink. Before using these methods, use the GetFormat method to test whether the current contents of the Clipboard matches the specified format.

  • You tried to use the GetData method or SetData method with a Clipboard format other than vbCFBitmap, vbCFDIB, or vbCFMetafile. Before using these methods, use the GetFormat method to test whether the current contents of the Clipboard matches the specified graphics format.


Specified library or project already referenced

 Copy code hover
[image]

Specified library or project already referenced
Send feedback

The Add References dialog box displays referenced libraries and projects. This error has the following cause and solution:

  • You chose the Browse button in the Add References dialog box, then selected a type library or project that was already listed in the Available References section of the Add References dialog box.

    To make a project or type library part of your project, display the References dialog box and make sure the type library or project name is checked.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Statement invalid inside Type block

 Copy code hover
[image]

Statement invalid inside Type block
Send feedback

Only element names, their As type clauses, and comments are allowed within a Type...End Type statement block. This error has the following cause and solution:

  • You placed an invalid statement in user-defined type definition.

    Remove anything that isn't a comment, an element name, or an As type clause.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Statement invalid outside Type block

 Copy code hover
[image]

Statement invalid outside Type block
Send feedback

The syntax for declaring variables outside a Type...End Type statement block is different from the syntax for declaring the elements of the user-defined type. This error has the following causes and solutions:

  • You tried to declare a variable outside a Type...End Type block or outside a statement. When declaring a variable with an As clause outside a Type...End Type block, use one of the declaration statements, Dim, ReDim, Static, Public, or Private. For example, the first declaration of MyVar in the following code generates this error; the second and third declarations of MyVar are valid:

    Copy code Copy code
    MyVar As Double ' Invalid declaration syntax.

Dim MyVar As Double

Type AType
MyVar As Double ' This is valid declaration syntax
End Type ' because it's inside a Type block.

  • You used an End Type statement without a corresponding Type statement. Check for an unmatched End Type, and either precede its block with a Type statement, or delete the End Type statement if it isn't needed.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Statement too complex

 Copy code hover
[image]

Statement too complex
Send feedback

Visual Basic is unable to analyze this statement. This error has the following causes and solutions:

  • Your statement can't be parsed due to its complexity. Try breaking the statement into several smaller components or replace complex conditional clauses with a combination of logical operators and If...Then...Else statements.

  • Your statement or function uses too many nested function calls. Make function calls earlier and assign the results to specific variables; then use the variables in the statement that is causing the complexity error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Statements or labels invalid between Select Case and first Case

 Copy code hover
[image]

Statements or labels invalid between Select Case and first Case
Send feedback

You can place nothing but a comment between the Select Case statement and the first Case clause. This error has the following cause and solution:

  • You placed a statement between Select Case and its first Case clause. For example:

    Copy code Copy code
    Select Case SomeVar
' This is a comment and is valid.
Stop ' Even a Stop statement is invalid here.
Case SomeValue
. . .
End Select

    The Select Case statement must be immediately followed by its first Case statement. If the intervening expression is a comment, precede it with a comment delimiter ('). Otherwise, place the expression where it belongs or delete it.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


String value too long to process; form load aborted

 Copy code hover
[image]

String value too long to process; form load aborted
Send feedback

A string embedded in the form being loaded was too long to process.


Sub, Function, or Property not defined (Error 35)

 Copy code hover
[image]

Sub, Function, or Property not defined (Error 35)
Send feedback

A Sub, Function, or Property procedure must be defined to be called. This error has the following causes and solutions:

  • You misspelled the name of your procedure.

    Check the spelling and correct it.

  • You tried to call a procedure from another project without explicitly adding a reference to that project in the References dialog box.

    To add a reference

    1. Display the References dialog box.

    2. Find the name of the project containing the procedure you want to call. If the project name doesn't appear in the References dialog box, click the Browse button to search for it.

    3. Click the check box to the left of the project name.

    4. Click OK.

  • The specified procedure isn't visible to the calling procedure. Procedures declared Private in one module can't be called from procedures outside the module. If Option Private Module is in effect, procedures in the module aren't available to other projects. Search to locate the procedure.

  • You declared a Windows dynamic-link library (DLL) routine or Macintosh code-resource routine, but the routine isn't in the specified library or code resource.

  • Check the ordinal (if you used one) or the name of the routine. Make sure your version of the DLL or Macintosh code-resource is the correct one. The routine may only exist in later versions of the DLL or Macintosh code-resource. If the directory containing the wrong version precedes the directory containing the correct one in your path, the wrong DLL or Macintosh code-resource is accessed. You gave the right DLL name or Macintosh code-resource, but it isn't the version that contains the specified function.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Subscript out of range (Error 9)

 Copy code hover
[image]

Subscript out of range (Error 9)
Send feedback

Elements of arrays and members of collections can only be accessed within their defined ranges. This error has the following causes and solutions:

  • You referenced a nonexistent array element. The subscript may be larger or smaller than the range of possible subscripts, or the array may not have dimensions assigned at this point in the application. Check the declaration of the array to verify its upper and lower bounds. Use the UBound and LBound functions to condition array accesses if you're working with arrays that are redimensioned. If the index is specified as a variable, check the spelling of the variable name.

  • You declared an array but didn't specify the number of elements. For example, the following code causes this error:

    Copy code Copy code
    Dim MyArray() As Integer
MyArray(8) = 234 ' Causes Error 9.

    Visual Basic doesn't implicitly dimension unspecified array ranges as 0 - 10. Instead, you must use Dim or ReDim to specify explicitly the number of elements in an array.

  • You referenced a nonexistent collection member. Try using the For Each...Next construct instead of specifying index elements.

  • You used a shorthand form of subscript that implicitly specified an invalid element. For example, when you use the ! operator with a collection, the ! implicitly specifies a key. For example, object!keyname.value is equivalent to object.item(keyname).value. In this case, an error is generated if keyname represents an invalid key in the collection. To fix the error, use a valid key name or index for the collection.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Syntax error

 Copy code hover
[image]

Syntax error
Send feedback

Visual Basic can't determine what action to take. This error has the following causes and solutions:

  • A keyword or argument is misspelled.

    Keywords and the names of named arguments must exactly match those specified in their syntax specifications. Check online Help, and then correct the spelling.

  • Punctuation is incorrect. For example, when you omit optional arguments positionally, you must substitute a comma (,) as a placeholder for the omitted argument.

  • A procedure isn't defined.

    Check the spelling of the procedure name.

  • You tried to specify both Optional and ParamArray in the same procedure declaration. A ParamArray argument can't be Optional. Choose one and delete the other.

  • You tried to define an event procedure with an Optional or ParamArray parameter. Remove the Optional or ParamArray keyword from the parameter specification.

  • You tried to use a named argument in a RaiseEvent statement. Events do not support named arguments.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


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

 Copy code hover
[image]

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

A .dll file provided by the operating system; for example, DDEML.DLL, VERSION.DLL, or WINSPOOL.DRV couldn't be found. This error has the following causes and solutions:

  • The file isn't on the proper path. Ensure the DLL is on the Windows System path.

  • The DLL is corrupted or was deleted. Reload the DLL.

  • There isn't enough memory or swap space. Try to free up some memory by closing other applications.


System error 'item'

 Copy code hover
[image]

System error 'item'
Send feedback

Visual Basic encountered an error that was generated by the system or an external component.


The .VBP file for this project contains an invalid or corrupt library references ID

 Copy code hover
[image]

The .VBP file for this project contains an invalid or corrupt library references ID
Send feedback

When you save a project for which a reference has been selected from the References dialog box, an entry is made in the project's .vbp file (called the .mak file in earlier versions of Visual Basic). For example, the entry for a data access object is:

Copy code Copy code
Reference=*\G{00025E01-0000-0000-C000-000000000046}#0.0#0#C:\WINDOWS\SYSTEM\DAO2516.DLL#Microsoft
DAO 2.5 Object Library

This error occurs when such a reference has been edited or corrupted. This error has the following cause and solution:

  • A reference in the .vbp file has become invalid. Delete the incorrect line from the .vbp file and check the appropriate object library in the References dialog box from the Tools menu. Then save the project, and the correct information will be entered in the .vbp file.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The ActiveX Designer's Type Information does not match what was saved. Unable to Load.

 Copy code hover
[image]

The ActiveX Designer's Type Information does not match what was saved. Unable to Load.
Send feedback

This error has the following causes and solutions:

  • The project could not be loaded because the ActiveX designer's Type information doesn't match what was saved. This can be due to a corrupt file. Attempt to load a backup copy of the project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The application description can't be more than 2000 characters long

 Copy code hover
[image]

The application description can't be more than 2000 characters long
Send feedback

You can't have an application description longer than 2000 characters long. Delete some characters from the description.


The binary compatibility DLL or EXE contains a parameter type or return type whose definition cannot be found

 Copy code hover
[image]

The binary compatibility DLL or EXE contains a parameter type or return type whose definition cannot be found
Send feedback

If you have a Binary Compatible server which contains a parameter or return type that is contained in another DLL, you must be careful when recompiling it. This warning has the following cause and solution:

  • When you set Binary Compatibility on a project and then recompile the project, Project Compatibility is set automatically, changing the interface's internal GUID. Since this is not a visible change, this can be an unexpected error. Basically, this error occurs when a project's binary compatible DLL or EXE has a typelib with a broken reference. Broken references can occur when a referenced typelib is overwritten by another file (such as a re-compiled DLL/EXE), when you delete the typelib file, or when you move a referencing typelib over to a machine, but either don't move the referenced typelib or don't register the referenced typelib. One possible fix is to obtain a copy of the referenced typelib onto your machine and register it. You won't be able to use the old one because it was overwritten on recompile. Failing this, all that can be done is to stop using the DLL/EXE as your binary compatible version.


The binary compatibility DLL or EXE contains an Implements type whose definition cannot be found

 Copy code hover
[image]

The binary compatibility DLL or EXE contains an Implements type whose definition cannot be found
Send feedback

If you have a Binary Compatible server which implements an interface that is contained in another DLL, you must be careful when recompiling it. This warning has the following cause and solution:

  • The other DLL was recompiled as Project Compatible which changes the interface GUID. Since this is not a visible change, this can be an unexpected error. This can also occur if someone gives you a Project Compatible DLL to reference. Basically, this error occurs when a project's binary compatible DLL or EXE has a typelib with a broken reference. Broken references can occur when a referenced typelib is overwritten by another file (such as a re-compiled DLL/EXE), when you delete the typelib file, or when you move a referencing typelib over to a machine, but either don't move the referenced typelib or don't register the referenced typelib. One possible fix is to obtain a copy of the referenced typelib onto your machine and register it. You won't be able to use the old one because it was overwritten on recompile. Failing this, all that can be done is to stop using the DLL/EXE as your binary compatible version.


The code in this project must be updated for use on 64-bit systems

 Copy code hover
[image]

The code in this project must be updated for use on 64-bit systems
Send feedback

Complete error message:

The code in this project must be updated for use on 64-bit systems. Please review and update Declare statements and then mark them with the PtrSafe attribute.

All Declare Statements must now include the PtrSafe keyword when running in 64-bit versions of Microsoft Office. The PtrSafe keyword indicates a Declare statement is safe to run in 64-bit versions of Microsoft Office.

Adding the PtrSafe keyword to a Declare statement only signifies the Declare statement explicitly targets 64-bits, all data types within the statement that need to store 64-bits (including return values and parameters) must still be modified to hold 64-bit quantities using either LongLong for 64-bit integrals or LongPtr for pointers and handles.


The current project does not support files of this type

 Copy code hover
[image]

The current project does not support files of this type
Send feedback

This error has the following causes and solutions:

  • The file you tried to open is not a valid project file, or is a project file that contains features not supported by this Visual Basic host application and Visual Basic Environment. Make sure the project file you want to open is a valid project file (one you created and saved within the same Visual Basic host application and Visual Basic Environment).

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The edit may make the object module incompatible with the previously specified compatible ActiveX component

 Copy code hover
[image]

The edit may make the object module incompatible with the previously specified compatible ActiveX component
Send feedback

If a Compatible ActiveX component already exists as a previously distributed executable file or dynamic-link library (DLL), you must be careful not to change its interface. This warning has the following cause and solution:

  • You are trying to edit the code of an object module that already is represented by an executable file.

    If you make changes that affect the interface to the object, the class will not be upward compatible with the previous version and so it will not be possible to use the new version in place of the old version for compiled code.

    In Visual Basic, the name of the Compatible ActiveX component appears in the dialog box displayed when you choose Project Options from the Tools menu.

    Important note Important

    To accept the edit, click OK in the error message dialog box. If you want to undo the edit, click the Cancel button.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The file 'item' is marked as a version not supported by the current version of Visual Basic and won't be loaded

 Copy code hover
[image]

The file 'item' is marked as a version not supported by the current version of Visual Basic and won't be loaded
Send feedback

You tried to load a form from Visual Basic version 1.0 or a form from a version later than this version of Visual Basic. This is not supported.


The file 'item' is out of date. This program requires a later version (Error 368)

 Copy code hover
[image]

The file 'item' is out of date. This program requires a later version (Error 368)
Send feedback

An ActiveX control was found to be out of date. This error has the following cause and solution:

  • The number of properties in the current version of the ActiveX control don't match the expected number of properties.

    Replace the ActiveX control with a later version.


The file 'item' was not registerable as an ActiveX Component.

 Copy code hover
[image]

The file 'item' was not registerable as an ActiveX Component.
Send feedback

This error has the following causes and solutions:

  • You tried to register a control or dynamic-link library (.dll) that is not a valid ActiveX component. Make sure that you have the correct control or .dll. Contact the ActiveX component's vendor for more information.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The form class contained in the specified file is not supported in Visual Basic for Applications; the file can't be loaded.

 Copy code hover
[image]

The form class contained in the specified file is not supported in Visual Basic for Applications; the file can't be loaded.
Send feedback

Visual Basic for Applications only supports UserForm form objects. This error has the following cause and solution:

  • You are trying to load a form from an earlier version of Visual Basic or a form from a current standalone version of Visual Basic. It is probably easiest to redesign the form using the UserForm tools within Visual Basic for Applications. If you can save the form in ASCII format, you may be able to modify the form and import it. However, you must completely understand the formats and limitations of the various form packages.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The library containing this symbol is not referenced by the current project, so the symbol is undefined. Would you like to add a reference to the containing library now?

 Copy code hover
[image]

The library containing this symbol is not referenced by the current project, so the symbol is undefined. Would you like to add a reference to the containing library now?
Send feedback

Type and object information is contained in libraries. This error has the following causes and solutions:

  • A definition for this symbol exists in a type library.

    If you want to define the symbol as contained in the library mentioned, click OK to add the reference to the library.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The load behavior for 'item' could not be updated because of current registry permissions.

 Copy code hover
[image]

The load behavior for 'item' could not be updated because of current registry permissions.
Send feedback

This error has the following causes and solutions:

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

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The project file 'item' is corrupt and can't be loaded

 Copy code hover
[image]

The project file 'item' is corrupt and can't be loaded
Send feedback

Visual Basic can't read the project file. This can occur if the file has been modified by an editor outside of Visual Basic. To fix the problem, undo any changes made to the file.


The project file 'item1' contains invalid 'item2' key value

 Copy code hover
[image]

The project file 'item1' contains invalid 'item2' key value
Send feedback

The specified key value is invalid. Please change it.


The project file 'item1' contains invalid 'item2' key value. Valid range is 0 to 'item3'

 Copy code hover
[image]

The project file 'item1' contains invalid 'item2' key value. Valid range is 0 to 'item3'
Send feedback

The range of key values is restricted. Keep the key value within the range specified.


The project file 'item1' contains invalid key 'item2'.

 Copy code hover
[image]

The project file 'item1' contains invalid key 'item2'.
Send feedback

This error has the following causes and solutions:

  • The Visual Basic project (.vbp) file contains a key that Visual Basic doesn't recognize. The file may be corrupt. Install a backup copy of the specified file or modify the file using a text editor to correct the error. Modifying a Visual Basic file in an editor other than Visual Basic may corrupt the file. This is recommended only for advanced users.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The project file 'item1' contains invalid key 'item2'. The project can't be loaded

 Copy code hover
[image]

The project file 'item1' contains invalid key 'item2'. The project can't be loaded
Send feedback

You can't load the project while the project file contains the invalid key.


The project name is too long. Name has been truncated

 Copy code hover
[image]

The project name is too long. Name has been truncated
Send feedback

If a project name exceeds permitted length, it is truncated to the maximum permitted length.


The remote server machine does not exist or is unavailable (Error 462)

 Copy code hover
[image]

The remote server machine does not exist or is unavailable (Error 462)
Send feedback

The CreateObject function requires a valid server. This error has the following cause and solution:

  • A server parameter was specified, but the server could not be either reached or found.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The selected Add-In has not been confirmed to be 'Command Line Safe,' and may require some user intervention (possible UI)

 Copy code hover
[image]

The selected Add-In has not been confirmed to be 'Command Line Safe,' and may require some user intervention (possible UI)
Send feedback

This error has the following causes and solutions:

  • "Command-line safe" means that the add-in is registered in a way to indicate that it contains no user interfaces that require user input when Visual Basic is invoked through a command-line. A user interface can interfere with the operation of unattended processes (such as build scripts). If you don't indicate that an add-in is command-line safe (even if it is command-line safe), when a user selects your add-in and then Command Line in the Load Behavior box, they'll receive the warning message. This isn't a serious problem, but merely a warning to the user that the selected add-in might possibly contain UI elements that can pop up unexpectedly and halt their automated scripts by pausing for user input. To specify that an add-in is command-line safe, author it that way (you can use the Add-In designer for this), or manually change the value in the registry key.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The specified file could not be loaded.

 Copy code hover
[image]

The specified file could not be loaded.
Send feedback

Not all files can be loaded in Visual Basic for Applications. This error has the following cause and solution:

  • The file you are trying to load has a format that Visual Basic can't interpret, or the file is corrupt. You can't load the file.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The specified object can't be used as an owner form for Show() (Error 371)

 Copy code hover
[image]

The specified object can't be used as an owner form for Show() (Error 371)
Send feedback

You must use an appropriate object with the Show method.


The specified region has been searched

 Copy code hover
[image]

The specified region has been searched
Send feedback

When you click the Find Next and Replace buttons in the Replace dialog box, the total number of replacements isn't specified. This condition has the following cause and effect:

  • When doing a search and replace operation, you can specify the region to be covered: a selection, a procedure, a module, or a project.

    If a region is selected, it is the default search region. If no region is selected, the current module is the default search region. To change the scope of a search, select a different option in the Replace dialog box.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The specified region has been searched and 1 replacement was made

 Copy code hover
[image]

The specified region has been searched and 1 replacement was made
Send feedback

When you click the Replace All button in the Replace dialog box, this message specifies the total number of replacements. This condition has the following cause and effect:

  • During the search and replace operation, only one instance of the specified text was found, and the replacement was made. You can specify the region to be covered: a selection, a procedure, a module, or a project.

    If a region is selected, it is the default search region. If no region is selected, the current module is the default search region. To change the scope of a search, select a different option in the Replace dialog box.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The specified region has been searched and the replacements were made

 Copy code hover
[image]

The specified region has been searched and the replacements were made
Send feedback

When you click the Replace All button in the Replace dialog box, this message specifies the total number of replacements. This condition has the following cause and effect:

  • When doing a search and replace operation, you can specify the region to be covered: a selection, a procedure, a module, or a project.

    If a region is selected, it is the default search region. If no region is selected, the current module is the default search region. To change the scope of a search, select a different option in the Replace dialog box.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Translation failed. Please check the trnslate.log file for more information.

 Copy code hover
[image]

Translation failed. Please check the trnslate.log file for more information.
Send feedback

Current versions of Visual Basic only perform translation for backward compatibility. This error has the following causes and solutions:

  • The translation failed unexpectedly. This usually occurs because of a broken type library reference. More details should be available in the specified translation log.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This action will reset your project, proceed anyway?

 Copy code hover
[image]

This action will reset your project, proceed anyway?
Send feedback

You can edit code in break mode, but some edits prevent continuing execution. This error has the following cause and solution:

  • You attempted an edit that prevents continued execution, for example, you declared a static variable.

    If you choose Yes, execution will terminate and you can edit your code. If you choose No, you can continue running the code from the point at which it was suspended.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This array is fixed or temporarily locked (Error 10)

 Copy code hover
[image]

This array is fixed or temporarily locked (Error 10)
Send feedback

Not all arrays can be redimensioned. Even arrays specifically declared to be dynamic and arrays within Variant variables are sometimes locked temporarily. This error has the following causes and solutions:

  • You tried to use ReDim to change the number of elements of a fixed-size array . For example, in the following code, the fixed array FixedArr is received by SomeArr in the NextOne procedure, and then an attempt is made to resize SomeArr :

    Copy code Copy code
    Sub FirstOne
Dim FixedArr(25) As Integer    ' Create a fixed-size array and
NextOne FixedArr()    ' pass it to another procedure.
End Sub

Sub NextOne(SomeArr() As Integer)
ReDim SomeArr(35)        ' Error 10 occurs here.
. . .
End Sub

    Make the original array dynamic rather than fixed by declaring it with ReDim (if the array is declared within a procedure), or by declaring it without specifying the number of elements (if the array is declared at module level).

  • You tried to redimension a module-level dynamic array, in which one element has been passed as an argument to a procedure. For example, in the following code, ModArray is a dynamic, module-level array whose forty-fifth element is being passed by reference to the Test procedure:

    Copy code Copy code
    Dim ModArray () As Integer    ' Create a module-level dynamic array.
. . .

Sub AliasError()
ReDim ModArray (1 To 73) As Integer
Test ModArray (45)    ' Pass an element of the module-level
' array to the Test procedure.
End Sub

Sub Test(SomeInt As Integer)
ReDim ModArray (1 To 40) As Integer  ' Error occurs here.
End Sub

    There is no need to pass an element of the module-level array in this case, since it's visible within all procedures in the module. However, if an element is passed, the array is locked to prevent a deallocation of memory for the reference parameter within the procedure, causing unpredictable behavior when the procedure returns.

  • You attempted to assign a value to a Variant variable containing an array, but the Variant is currently locked. For example, if your code uses a For Each...Next loop to iterate over a variant containing an array, the array is locked on entry into the loop, and then released at the termination of the loop:

    Copy code Copy code
    SomeArray = Array(9,8,7,6,5,4,3,2,1)

For Each X In SomeArray
SomeArray = 301    ' Causes error since array is locked.
Next X

    Use a For...Next rather than a For Each...Next loop to iterate. When an array is the object of a For Each...Next loop, you can read the array, but not write to it.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This command will stop the debugger.

 Copy code hover
[image]

This command will stop the debugger.
Send feedback

Some commands and actions cause Visual Basic to stop analyzing code. This error has the following cause and solution:

  • Some edits, like declaring a Static variable, and some commands, like those for adding a new module or form, cause running or suspended code to stop.

    If you don't want to stop running code, don't add or execute the command.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This component doesn't raise any events

 Copy code hover
[image]

This component doesn't raise any events
Send feedback

An event procedure must correspond to an event that can be raised by an object. This error has the following cause and solution:

  • You wrote an event procedure for an object that doesn't raise events. You can't write an event procedure that doesn't correspond to an event.

  • You tried to use WithEvents on a class that doesn't raise events.

    You can't use WithEvents on a class that doesn't raise events.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This component doesn't support this set of events (Error 459)

 Copy code hover
[image]

This component doesn't support this set of events (Error 459)
Send feedback

Not every component supports client sinking of events. This error has the following cause and solution:

  • You tried to use a WithEvents variable with a component that can't work as an event source for the specified set of events. For example, you may be sinking events of an object, then create another object that Implements the first object. Although you might think you could sink the events from the implemented object, that isn't automatically the case. Implements only implements an interface for methods and properties. You can't sink events for a component that doesn't source events.

  • WithEvents isn't supported for Private UserControls, because the type-info needed to raise the ObjectEvent isn't available at runtime.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This control can only be used with 'item' designers

 Copy code hover
[image]

This control can only be used with 'item' designers
Send feedback

This error has the following causes and solutions:

  • The control you've chosen works only with the indicated designer. You must choose another control or a different designer.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This control cannot be used with 'item' designers

 Copy code hover
[image]

This control cannot be used with 'item' designers
Send feedback

This error has the following causes and solutions:

  • The control you've chosen doesn't work with the indicated designer. You must choose another control or a different designer.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This designer cannot be used because it uses features that are not supported in this version of Visual Basic

 Copy code hover
[image]

This designer cannot be used because it uses features that are not supported in this version of Visual Basic
Send feedback

This error has the following causes and solutions:

  • The designer you've chosen is not supported in this version of Visual Basic. You must use a different designer, or one designed for the indicated version of Visual Basic.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This document was opened with Macros Disabled

 Copy code hover
[image]

This document was opened with Macros Disabled
Send feedback

A host application may disable or enable macros. This error has the following causes and solutions:

  • You opened the document with Macros Disabled. Close the document, and then reopen it with Enable Macros.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This edit requires a Reset

 Copy code hover
[image]

This edit requires a Reset
Send feedback

In most cases, you can edit code and continue running the code from the point of the edit. This error has the following causes and solutions:

  • You made a change to your code that requires you to restart the code from the initialization point. This might occur if you broke up the code in a procedure and the current execution line is no longer contained in the same procedural context as it was when execution was suspended.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This feature requires Internet Explorer 'item' or greater. You can obtain the latest version from www.microsoft.com

 Copy code hover
[image]

This feature requires Internet Explorer 'item' or greater. You can obtain the latest version from www.microsoft.com
Send feedback

This error has the following causes and solutions:

  • You must have the indicated version of Internet Explorer for this feature to work correctly. Check http://www.microsoft.com for the latest available version of Internet Explorer.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This interaction between compiled and design environment components is not supported

 Copy code hover
[image]

This interaction between compiled and design environment components is not supported
Send feedback

This error has the following causes and solutions:

  • This occurs when two components are running together, where one component (such as a form or a UserControl) was previously compiled and is now running using the runtime (msvbvm60.dll), and the other component is being run in the IDE. For example, a compiled UserControl running on a form in the IDE. The problem occurs because the internal memory structure between an item running in the IDE and a compiled object is slightly different and not always compatible. In general, though, you shouldn't encounter a problem with this unless you are passing an instance of a UserControl (Me) to a host form or other component through a Property or Sub procedure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This key is already associated with an element of this collection (Error 457)

 Copy code hover
[image]

This key is already associated with an element of this collection (Error 457)
Send feedback

A key is a string specified in the Add method that uniquely identifies a specific member of a collection. This error has the following cause and solution:

  • You specified a key for a collection member that already identifies another member of the collection. Choose a different key for this member.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This project is currently referenced by another project and cannot be closed

 Copy code hover
[image]

This project is currently referenced by another project and cannot be closed
Send feedback

This error has the following causes and solutions:

  • The indicated project that you've attempted to close is being referenced by another project. Close it after you remove the reference from the other project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This VBA project was created while running VBA in a different application. You may only open it from inside the same application in which it was created.

 Copy code hover
[image]

This VBA project was created while running VBA in a different application. You may only open it from inside the same application in which it was created.
Send feedback

This error has the following causes and solutions:

  • The file you tried to open is a project file that was created within another host application. Make sure the project file you want to open is one you created and saved within the same Visual Basic host application.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Too many arguments

 Copy code hover
[image]

Too many arguments
Send feedback

A procedure can have only 60 arguments. This error has the following cause and solution:

  • You specified more than 60 arguments. If you must specify more arguments, define a user-defined type to collect multiple arguments of different types, or use a ParamArray as the final argument and pass multiple values to it. You can also pass multiple arguments by placing them in an array.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Too many dimensions

 Copy code hover
[image]

Too many dimensions
Send feedback

Arrays can have no more than 60 dimensions. This error has the following causes and solutions:

  • You tried to declare an array with more than 60 dimensions. Reduce the number of dimensions.

  • Your array declaration is within the specified limits, but there isn't enough memory to actually create the array. Either make more memory available or reduce the number of dimensions. If your array is an array of Variant type or an array contained within a Variant, you may be able to create the array with the same number of dimensions by redeclaring it with the data type of its elements. For example, if it contains only integers, declaring it as an array of Integer type uses less memory than if each element is a Variant.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Too many DLL application clients

 Copy code hover
[image]

Too many DLL application clients
Send feedback

The dynamic-link library (DLL) for Visual Basic can only accommodate access by 50 host applications at a time. This error has the following cause and solution:

  • Your application and other applications that are Visual Basic hosts (some of which may be accessed by your application) are all attempting to access the Visual Basic DLL at the same time. Reduce the number of open applications accessing Visual Basic.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Too many files (Error 67)

 Copy code hover
[image]

Too many files (Error 67)
Send feedback

There is a limit to the number of disk files that can be open at one time. This error has the following causes and solutions:

  • MS-DOS operating system: More files have been created in the root directory than the operating system permits. The MS-DOS operating system limits the number of files that can be in the root directory, usually 512. If your program is opening, closing, or saving files in the root directory, change your program so that it uses a subdirectory.

  • MS-DOS operating system: More files have been opened than the number specified in the files= setting in your CONFIG.SYS file. Increase the number specified in the files= setting in your CONFIG.SYS file and restart your computer.

  • Macintosh: Your program tried to open more than 40 files. On the Macintosh, the standard limit is 40 files. This limit can be changed using a utility to modify the MaxFiles parameter of the boot block.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Too many line continuations

 Copy code hover
[image]

Too many line continuations
Send feedback

There is a limit to the number of lines you can join with line-continuation characters. This error has the following cause and solution:

  • Your code has more than 25 physical lines lines joined with line-continuation characters, or more than 24 consecutive line-continuation characters in a single line. Make some of the constituent lines physically longer to reduce the number of line-continuation characters needed, or break the construct into more than one statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Too many local, nonstatic variables

 Copy code hover
[image]

Too many local, nonstatic variables
Send feedback

Local, nonstatic variables are variables that are defined within a procedure and reinitialized each time the procedure is called. This error has the following cause and solution:

  • The sum of the memory requirements for this procedure's local, nonstatic variables and compiler-generated temporary variables exceeds 32K. Declare some of your variables with the Static statement where appropriate. Static variables retain their value between procedure invocations because they are allocated from different memory resources than nonstatic variables.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Too many module-level variables

 Copy code hover
[image]

Too many module-level variables
Send feedback

Module-level variables are those declared in the Declarations section of a module, before the module's procedures. This error has the following cause and solution:

  • The sum of the memory requirements for all module-level variables in this module exceeds 64K.

    This is the storage limit for this module. If appropriate, you can declare some of your variables as Public in another module, or if some module-level variables are used only in one procedure, you can declare them within that procedure. If you declared variables at module level because you want them to retain their value between procedure invocations, you can instead declare them as Static within the procedure in which they are referenced.

    Note Note

    Available space can vary among operating systems.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Trappable Errors

 Copy code hover
[image]

Trappable Errors
Send feedback

Trappable errors can occur while an application is running. Some trappable errors can also occur during development or compile time. You can test and respond to trappable errors using the On Error statement and the Err object. Unused error numbers in the range 1 - 1000 are reserved for future use by Visual Basic.

Code | Message
3 | Return without GoSub
5 | Invalid procedure call
6 | Overflow
7 | Out of memory
9 | Subscript out of range
10 | This array is fixed or temporarily locked
11 | Division by zero
13 | Type mismatch
14 | Out of string space
16 | Expression too complex
17 | Can't perform requested operation
18 | User interrupt occurred
20 | Resume without error
28 | Out of stack space
35 | Sub, Function, or Property not defined
47 | Too many code resource or DLL application clients
48 | Error in loading code resource or DLL
49 | Bad code resource or DLL calling convention
51 | Internal error
52 | Bad file name or number
53 | File not found
54 | Bad file mode
55 | File already open
57 | Device I/O error
58 | File already exists
59 | Bad record length
61 | Disk full
62 | Input past end of file
63 | Bad record number
67 | Too many files
68 | Device unavailable
70 | Permission denied
71 | Disk not ready
74 | Can't rename with different drive
75 | Path/File access error
76 | Path not found
91 | Object variable or With block variable not set
92 | For loop not initialized
93 | Invalid pattern string
94 | Invalid use of Null
97 | Can't call Friend procedure on an object that is not an instance of the defining class
98 | A property or method call cannot include a reference to a private object, either as an argument or as a return value
298 | System resource or DLL could not be loaded
320 | Can't use character device names in specified file names
321 | Invalid file format
322 | Can't create necessary temporary file
325 | Invalid format in resource file
327 | Data value named not found
328 | Illegal parameter; can't write arrays
335 | Could not access system registry
336 | Component not correctly registered
337 | Component not found
338 | Component did not run correctly
360 | Object already loaded
361 | Can't load or unload this object
363 | Control specified not found
364 | Object was unloaded
365 | Unable to unload within this context
368 | The specified file is out of date. This program requires a later version
371 | The specified object can't be used as an owner form for Show
380 | Invalid property value
381 | Invalid property-array index
382 | Property Set can't be executed at run time
383 | Property Set can't be used with a read-only property
385 | Need property-array index
387 | Property Set not permitted
393 | Property Get can't be executed at run time
394 | Property Get can't be executed on write-only property
400 | Form already displayed; can't show modally
402 | Code must close topmost modal form first
419 | Permission to use object denied
422 | Property not found
423 | Property or method not found
424 | Object required
425 | Invalid object use
429 | Component can't create object or return reference to this object
430 | Class doesn't support Automation
432 | File name or class name not found during Automation operation
438 | Object doesn't support this property or method
440 | Automation error
442 | Connection to type library or object library for remote process has been lost
443 | Automation object doesn't have a default value
445 | Object doesn't support this action
446 | Object doesn't support named arguments
447 | Object doesn't support current locale setting
448 | Named argument not found
449 | Argument not optional or invalid property assignment
450 | Wrong number of arguments or invalid property assignment
451 | Object not a collection
452 | Invalid ordinal
453 | Specified code resource not found
454 | Code resource not found
455 | Code resource lock error
457 | This key is already associated with an element of this collection
458 | Variable uses a type not supported in Visual Basic
459 | This component doesn't support the set of events
460 | Invalid Clipboard format
461 | Method or data member not found
462 | The remote server machine does not exist or is unavailable
463 | Class not registered on local machine
480 | Can't create AutoRedraw image
481 | Invalid picture
482 | Printer error
483 | Printer driver does not support specified property
484 | Problem getting printer information from the system. Make sure the printer is set up correctly
485 | Invalid picture type
486 | Can't print form image to this type of printer
520 | Can't empty Clipboard
521 | Can't open Clipboard
735 | Can't save file to TEMP directory
744 | Search text not found
746 | Replacements too long
31001 | Out of memory
31004 | No object
31018 | Class is not set
31027 | Unable to activate object
31032 | Unable to create embedded object
31036 | Error saving to file
31037 | Error loading from file


Type mismatch (Error 13)

 Copy code hover
[image]

Type mismatch (Error 13)
Send feedback

Visual Basic is able to convert and coerce many values to accomplish data type assignments that weren't possible in earlier versions. However, this error can still occur and has the following causes and solutions:

  • The variable or property isn't of the correct type. For example, a variable that requires an integer value can't accept a string value unless the whole string can be recognized as an integer.

    Try to make assignments only between compatible data types. For example, an Integer can always be assigned to a Long, a Single can always be assigned to a Double, and any type (except a user-defined type) can be assigned to a Variant.

  • An object was passed to a procedure that is expecting a single property or value.

    Pass the appropriate single property or call a method appropriate to the object.

  • A module or project name was used where an expression was expected, for example:

    Copy code Copy code
    Debug.Print MyModule

    Specify an expression that can be displayed.

  • You attempted to mix traditional Basic error handling with Variant values having the Error subtype (10, vbError), for example:

    Copy code Copy code
    Error CVErr(n)

    To regenerate an error, you must map it to an intrinsic Visual Basic or a user-defined error, and then generate that error.

  • A CVErr value can't be converted to Date. For example:

    Copy code Copy code
    MyVar = CDate(CVErr(9))

    Use a Select Case statement or some similar construct to map the return of CVErr to such a value.

  • At run time, this error typically indicates that a Variant used in an expression has an incorrect subtype, or a Variant containing an array appears in a Print # statement.

    To print arrays, create a loop that displays each element individually.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Type mismatch: array or user-defined type expected

 Copy code hover
[image]

Type mismatch: array or user-defined type expected
Send feedback

The type of an argument or parameter includes whether or not it is an array or a user-defined type. This error has the following cause and solution:

  • Your argument specified a single element of an array or user-defined type, or a simple variable, literal, or constant. However, it is being passed to a parameter that expects a whole array or user-defined type.

    Either change the argument or change the definition of the parameter.

  • Your argument specified an array or user-defined type, but it was not of the same type as the parameter. Either pass an array of the expected type or change the definition of the parameter declaration.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Type not supported in Visual Basic

 Copy code hover
[image]

Type not supported in Visual Basic
Send feedback

Not all types are supported in Visual Basic. This error has the following cause and solution:

  • You tried to use a type in your program that has no equivalent in Visual Basic for Applications. For example, Visual Basic has no pointer or unsigned integer type, so if you try to create a variable of one of those types from an object library, this error occurs. In the following example that follows, even though Rainbow may be a valid structure, Visual Basic can't create a variable of that type if it contains a type Visual Basic doesn't recognize:

    Copy code Copy code
    Dim MyVar As Rainbow    ' Causes error.

    If the type is a valid parameter type for a function in an object library, this error means only that you can't create a variable of that type in your own code. Although you can't always declare variables with a data type specified in an object's documentation, there is often a Visual Basic equivalent. For example, although Visual Basic has no pointer type, you can pass a pointer to a function to an API function by using the AddressOf operator. Also, check the Variant type's subtypes. You can often use them as equivalents of types not offered directly in Visual Basic. In some cases, however, Visual Basic simply has no equivalent. For example, data pointers aren't available.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Type-declaration character does not match declared data type

 Copy code hover
[image]

Type-declaration character does not match declared data type
Send feedback

The data type of a variable can't be changed by appending the type-declaration character for another type. This error has the following cause and solution:

  • You declared a variable of a specific type, referenced a variable of the same name in the same scope, and then appended an inconsistent type-declaration character.

    If you want to be able to change the type of data assigned to a variable, declare the variable as a Variant. If you simply appended an incorrect type-declaration character, delete or change it.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Type-declaration character not allowed

 Copy code hover
[image]

Type-declaration character not allowed
Send feedback

While using type-declaration characters is valid in Visual Basic, some data types (including Byte, Boolean, Date, Object, and Variant) have no associated type-declaration characters. This error has the following causes and solutions:

  • You tried to use a type-declaration character in the declaration of a variable that uses the As clause, for example, with Dim, Static, Public, and so on.

    Either remove the type-declaration character or remove the As clause.

  • You tried to use a type-declaration character in reference to a variable that was implicitly declared without a type-declaration character:

    Copy code Copy code
    MyVar = 20    ' Implicit declaration.
MyVar% = 25    ' Generates an error.
    Copy code Copy code
    Dim MyStr$
MyStr = "Because it was explicitly declared, the $ is optional."

    Either remove the type-declaration character or redeclare the original variable.

    Note Note

    If an explicit variable declaration contains a type-declaration character, inclusion of the character is optional in later references. For example:

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Type-declaration character required

 Copy code hover
[image]

Type-declaration character required
Send feedback

The necessity of using type-declaration characters depends on the form of the identifier's declaration. This error has the following cause and solution:

  • A variable that was originally implicitly declared with a type-declaration characters was referenced without a type-declaration character. For example:

    Copy code Copy code
    MyStr$ = "Implicit declaration"
MyStr = "Trying to refer to MyStr$, but error results" _
 & "from calling it MyStr."
    Copy code Copy code
    Dim MyStr$
MyStr = "Because it was explicitly declared, the $ is optional."

    Either make the declaration explicit, or add the type-declaration character to later references.

    Note Note

    If an explicit variable declaration contains a type-declaration character, inclusion of the character is optional in later references. For example:

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Unable to activate object (Error 31027)

 Copy code hover
[image]

Unable to activate object (Error 31027)
Send feedback

The object's source document can't be loaded, or the application that created the object isn't available.

This error occurs when you try to activate a linked object (set Action = 7) and the file specified in the SourceDoc property has been deleted or no longer exists.

This error also occurs when you activate an object (set Action = 7), and the action specified by the Verb property isn't valid. Some applications that provide objects may support different verbs, depending on the state of the application. All the verbs supported by an application are listed in the ObjectVerbs property list. However, some verbs may not be valid for the application's current state.


Unable to create embedded object (Error 31032)

 Copy code hover
[image]

Unable to create embedded object (Error 31032)
Send feedback

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

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


Unable to display Help

 Copy code hover
[image]

Unable to display Help
Send feedback

This error has the following causes and solutions:

  • If you're running WinHelp, the Windows Help application isn't available. If Winhelp.exe is on your machine, make sure it is on your path. If it isn't on your machine, run Microsoft Windows 9x or Microsoft Windows NT setup to install it.

  • If you're running HTMLHelp, if HH.exe is on your machine, make sure sure it is on your path. If it isn't on your computer, you must install it before you can view Help.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Unable to read from the disk

 Copy code hover
[image]

Unable to read from the disk
Send feedback

There is a general problem reading from a disk. This error has the following causes and solutions:

  • The disk drive door is improperly closed. If the disk is removable, check the drive door. Close it properly if necessary.

  • The disk may be inserted upside down. Reinsert the disk right-side up.

  • The disk may not be properly formatted. Reformat the disk if you are willing to lose the data it currently contains.

  • You are experiencing network problems. Try restarting your network.

  • You placed a disk of a certain density in a drive that can't read it. Use a different drive or copy the material you want to a disk that can be read on your drive.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Unable to unload within this context (Error 365)

 Copy code hover
[image]

Unable to unload within this context (Error 365)
Send feedback

In some situations you are not allowed to unload a form or a control on a form. This error has the following causes and solutions:

  • There is an Unload statement in the Paint event for the form or for a control on the form that has the Paint event. Remove the Unload statement from the Paint event.

  • There is an Unload statement in the Change, Click, or DropDown events of a ComboBox. Remove the Unload statement from the event.

  • There is an Unload statement in the Scroll event of an HScrollBar or VScrollBar control. Remove the Unload statement from the event.

  • There is an Unload statement in the Resize event of a Data, Form, MDIForm, or PictureBox control. Remove the Unload statement from the event.

  • There is an Unload statement in the Resize event of an MDIForm that is trying to unload an MDI child form. Remove the Unload statement from the event.

  • There is an Unload statement in the RePosition event or Validate event of a Data control. Remove the Unload statement from the event.

  • There is an Unload statement in the ObjectMove event of an OLE Container control. Remove the Unload statement from the event.


Unable to write Designer cache file 'item'; will just use regular files on Load

 Copy code hover
[image]

Unable to write Designer cache file 'item'; will just use regular files on Load
Send feedback

Your ActiveX designer was unable to write information to a cache file, so the designer will load using uncached information.

To improve performance the next time you start Visual Basic, an ActiveX designer writes a cache file. The designer couldn't write to the cache file due to low disk space or invalid permissions on the drive. Make sure you have enough disk space available and that you have write permissions to the drive. If the problem persists, contact the ActiveX designer's vendor.


Unable to write to the disk

 Copy code hover
[image]

Unable to write to the disk
Send feedback

There is a general problem writing to a disk. This error has the following causes and solutions:

  • The disk drive door is improperly closed. If the disk is removable, check the drive door. Close it properly if necessary.

  • The disk may be inserted upside down. Reinsert the disk right-side up.

  • The disk may not be properly formatted. Reformat the disk if you are willing to lose the data it currently contains.

  • You are experiencing network problems. Try restarting your network.

  • You placed a disk of a certain density in a drive that can't write to it. Use a different drive or copy the material you want to a disk that can be read on your drive.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Unexpected compile error

 Copy code hover
[image]

Unexpected compile error
Send feedback

This error has the following causes and solutions:

  • This error occurs when an unanticipated error occurs during compilation that cannot be handled by the compiler.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Unexpected error

 Copy code hover
[image]

Unexpected error
Send feedback

This error has the following causes and solutions:

  • An unanticipated error occurred. Try shutting down the system and restarting it.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Unexpected error occurred in code generator or linker

 Copy code hover
[image]

Unexpected error occurred in code generator or linker
Send feedback

This error has the following causes and solutions:

  • The code generator or linker caused an unexpected error. Click Yes to display the errors in Notepad. This error is most commonly caused by low disk space or other disk-related issues.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Unexpected error; please contact Microsoft Technical Support

 Copy code hover
[image]

Unexpected error; please contact Microsoft Technical Support
Send feedback

This condition may or may not be serious. This error has the following cause and solution:

  • An unanticipated error occurred in the host application or in Visual Basic. You don't have to assume that this error is serious. However, you should note the number of the error and report it to Microsoft Technical Support.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Unexpected error; quitting

 Copy code hover
[image]

Unexpected error; quitting
Send feedback

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


Unmatched brackets in search string

 Copy code hover
[image]

Unmatched brackets in search string
Send feedback

An opening bracket must be matched by a closing bracket. This error has the following cause and solution:

  • You opened a bracket pair in a search string, but did not close it with a matching closing bracket. Place a closing bracket in the appropriate place.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Unrecognized project language

 Copy code hover
[image]

Unrecognized project language
Send feedback

The specified code locale for the project to be loaded isn't currently supported by this application. This error has the following causes and solutions:

  • The project was created on a system that supports the code locale, but was then moved to a system where that code locale isn't recognized. For example, the ole2nls.dll on the current machine may be a version that doesn't recognize the code locale. Install the proper dynamic-link library (DLL) on the current system.

  • The correct object library for the project was not found.

    Make sure the correct object libraries are available, for example, make sure your path includes their directories.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


User interrupt occurred (Error 18)

 Copy code hover
[image]

User interrupt occurred (Error 18)
Send feedback

The process of breaking execution is useful, but if left unhandled, it results in termination of the application. This error has the following cause and solution:

  • A user pressed CTRL+BREAK or another interrupt key. In the development environment, continue execution. To provide for the occurrence of this condition at run time, handle the error in an appropriate way.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


User-defined type may not be passed ByVal

 Copy code hover
[image]

User-defined type may not be passed ByVal
Send feedback

User-defined types can only be passed by reference (the default), not by value. The error may not be reported until the call is made. This error has the following cause and solution:

  • You placed a ByVal keyword in the definition of a parameter that represented a user-defined type.

    Remove the ByVal keyword. To keep changes from being propagated back to the caller, Dim a temporary variable of the type and pass the temporary variable into the procedure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


User-defined type not defined

 Copy code hover
[image]

User-defined type not defined
Send feedback

You can create your own data types in Visual Basic, but they must be defined first in a Type...End Type statement or in a properly registered object library or type library. This error has the following causes and solutions:

  • You tried to declare a variable or argument with an undefined data type or you specified an unknown class or object.

    Use the Type statement in a module to define a new data type. If you are trying to create a reference to a class, the class must be visible to the project. If you are referring to a class in your program, you must have a class module of the specified name in your project. Check the spelling of the type name or name of the object.

  • The type you want to declare is in another module but has been declared Private. Move the definition of the type to a standard module where it can be Public.

  • The type is a valid type, but the object library or type library in which it is defined isn't registered in Visual Basic. Display the References dialog box, and then select the appropriate object library or type library. For example, if you don't check the Data Access Object in the References dialog box, types like Database, Recordset, and TableDef aren't recognized and references to them in code cause this error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


User-defined type without members not allowed

 Copy code hover
[image]

User-defined type without members not allowed
Send feedback

User-defined types must have at least one element. This error has the following cause and solution:

  • You specified an empty user-defined type in a Type...End Type definition. Check the Type statement for unintended comment delimiters.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Valid values are whole numbers from 1 to 32

 Copy code hover
[image]

Valid values are whole numbers from 1 to 32
Send feedback

You attempted to set the TabStop Width beyond the permitted range. A number between 1 and 32 (inclusive) is acceptable for this field.


Valid values are whole numbers from 2 to 60

 Copy code hover
[image]

Valid values are whole numbers from 2 to 60
Send feedback

You attempted to set the Grid Width or Grid Height beyond the permitted range. A number between 2 and 60 (inclusive) is acceptable for this field.


Variable not defined

 Copy code hover
[image]

Variable not defined
Send feedback

You use the Option Explicit statement to protect your modules from having undeclared variables and to eliminate the possibility of inadvertently creating new variables when typographical errors occur. This error has the following cause and solution:

  • You used an Option Explicit statement to require the explicit declaration of variables, but you used a variable without declaring it. Explicitly declare the variable, or change the spelling of the variable to match that of the intended variable.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Variable not yet created in this context

 Copy code hover
[image]

Variable not yet created in this context
Send feedback

A variable has to be created before it can be displayed in the Watch window or the Immediate window, and before it can have values assigned to it in the Immediate window. This error has the following causes and solutions:

  • You tried to display the value of a local variable that you just entered in your code before executing at least a Single Step command in break mode.

    Step into the code to force compilation of the new statement.

  • You tried to display the value of a local variable that you just added in a procedure farther down the call chain by moving to the procedure using the Calls dialog box.

    You have to actually return to the procedure before you can display the variable in its context.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Variable required. Can't assign to this expression

 Copy code hover
[image]

Variable required. Can't assign to this expression
Send feedback

This error typically occurs when you attempt to assign a value to something that can't accept the assignment. This error has the following causes and solutions:

  • You attempted to use a numeric expression as an argument to the Len function.

    The Len function doesn't accept a numeric expression, a numeric literal, or a binary numeric expression, but it does accept either a string or numeric variable, a string expression, or a variable of user-defined type.

  • You used a function call or an expression as an argument to Input #, Let, Get, or Put. For example, you may have used an argument that appears to be a valid reference to an array variable, but instead is a call to a function of the same name.

    Input #, Let, Get, and Put don't accept function calls as arguments.

  • You attempted to assign a value to an identifier previously declared as a constant.

    Choose another name for the identifier.

  • You tried to use a nonvariable as a loop counter in a For...Next construction. Use a variable as the counter.

  • You tried to assign a value to a read-only property or to an expression that consists of more than one variable (such as X + Y). An assignment places a value at a memory location. The specified expression must represent a single, writable location.

    Rewrite the assignment to a single variable name that can accept the data.

  • You tried to use an undeclared variable that is defined as a constant in a type library.

    Either use a different name for the variable, or declare it explicitly.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Variable uses a type not supported in Visual Basic (Error 458)

 Copy code hover
[image]

Variable uses a type not supported in Visual Basic (Error 458)
Send feedback

Not every variable that appears in a type library or object library can be used by every programming language. This error has the following cause and solution:

  • You tried to use a variable defined in a type library or object library that has a data type that isn't supported by Visual Basic.

    You can't use a variable of a type not recognized by Visual Basic in a Visual Basic program.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Version number missing or invalid; Visual Basic 5.0 assumed

 Copy code hover
[image]

Version number missing or invalid; Visual Basic 5.0 assumed
Send feedback

The version signature was not found, or the specified version isn't recognized. Make sure that the first line that is not blank or a comment in the ASCII form specifies the correct version.


Version numbers must be in the range 0 to 9999

 Copy code hover
[image]

Version numbers must be in the range 0 to 9999
Send feedback

This error has the following causes and solutions:

  • You tried to assign a negative number, a non-numeric character, or a number greater than 9999, as the Major, Minor, or Revision component of the Version number for a project in the Make tab of the Project Properties dialog box. Use a number between 0 and 9999 inclusive.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Visual Basic can't load 'item' because it is not in the system registry. Please ensure that all add-ins have been installed correctly.

 Copy code hover
[image]

Visual Basic can't load 'item' because it is not in the system registry. Please ensure that all add-ins have been installed correctly.
Send feedback

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


Warning: custom language settings not portable

 Copy code hover
[image]

Warning: custom language settings not portable
Send feedback

Not all language settings are portable. This warning has the following cause and solution:

  • You used a custom language setting in your code. When you choose a custom language/country setting for your code, the language conventions used in your code match those set in the Control Panel of your system. You can use custom code locale settings, but your code may not work in other locales or on other systems with different settings. The host application parses some strings based on the Control Panel settings of the machine on which it is running. If the Control Panel settings on the target machine aren't the same as those on the machine on which the code was written, strings parsed by a host application don't work, for example, code that depends on a locale-specific decimal separator. Therefore, you should not use a custom language setting unless you don't intend to send your code to other users. If you plan to send your code to other users, select a predefined locale.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Wend without While

 Copy code hover
[image]

Wend without While
Send feedback

Every Wend statement must be preceded by a matching While statement. This error has the following cause and solution:

  • You used a Wend statement without a preceding While statement. Check for an unterminated loop nested within the While...Wend loop that's causing the error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


While without Wend

 Copy code hover
[image]

While without Wend
Send feedback

A While statement is used without a corresponding Wend statement. This error has the following cause and solution:

  • You opened a While...Wend construct, but did not close it. Check for an incorrectly matched While...Wend structure inside the outer While...Wend structure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Windowless controls can't have menus.

 Copy code hover
[image]

Windowless controls can't have menus.
Send feedback

This error has the following causes and solutions:

  • You've attempted to place a menu on a windowless control, which is not allowed. To place a menu on a control, choose a windowed control.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


With object must be user-defined type, Object, or Variant

 Copy code hover
[image]

With object must be user-defined type, Object, or Variant
Send feedback

The With...End With block can't be used with all variable types. This error has the following cause and solution:

  • You tried to use a variable that was not of Object type, user-defined type, or Variant type containing an object within a With block.

    Check to see if you misspelled the name of the object, user-defined type, or Variant variable.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Wizards can't reference projects

 Copy code hover
[image]

Wizards can't reference projects
Send feedback

A Wizard can reference another Wizard, but cannot reference a project. This error has the following causes and solutions:

  • During a Make Wizard command, a reference to a project was found. Remove the reference to the project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Wrong number of arguments (Error 450)

 Copy code hover
[image]

Wrong number of arguments (Error 450)
Send feedback

The number of arguments to a procedure must match the number of parameters in the procedure's definition. This error has the following causes and solutions:

  • The number of arguments in the call to the procedure wasn't the same as the number of required arguments expected by the procedure. Check the argument list in the call against the procedure declaration or definition.

  • You specified an index for a control that isn't part of a control array.

    The index specification is interpreted as an argument but neither an index nor an argument is expected, so the error occurs. Remove the index specification, or follow the procedure for creating a control array. Set the Index property to a nonzero value in the control's property sheet or property window at design time.

  • You tried to assign a value to a read-only property, or you tried to assign a value to a property for which no Property Let procedure exists.

    Assigning a value to a property is the same as passing the value as an argument to the object's Property Let procedure. Properly define the Property Let procedure; it must have one more argument than the corresponding Property Get procedure. If the property is meant to be read-only, you can't assign a value to it.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Wrong number of dimensions

 Copy code hover
[image]

Wrong number of dimensions
Send feedback

You must reference an array with indexes corresponding to the same number of dimensions as appear in the array's declaration. This error has the following cause and solution:

  • You referred to an array with a different number of dimensions than it actually contains. For example, referring to an array as X(2,4) (an array with two dimensions) when it has been defined as Dim X(5) (an array with one), generates this error. Check the declaration of the array and, in the reference, include one index for each dimension in the declaration.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Wrong version of operating system; requires Windows NT 3.51 (build 'item1' or later) or Windows 95 (build 'item2' or later)

 Copy code hover
[image]

Wrong version of operating system; requires Windows NT 3.51 (build 'item1' or later) or Windows 95 (build 'item2' or later)
Send feedback

To run this version of Visual Basic, you must be running the specified build of Windows 95 or Windows NT version 3.51.


You must save a project before you can reference it.

 Copy code hover
[image]

You must save a project before you can reference it.
Send feedback

You can't add a reference to an unsaved project. This error has the following cause and solution:

  • You tried to add a reference while the project was unsaved. Save the project before adding the reference.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


You must terminate the #If block with an #End If

 Copy code hover
[image]

You must terminate the #If block with an #End If
Send feedback

#If is a conditional compilation directive. This error has the following cause and solution:

  • An #If block was detected that isn't terminated by an #End If. Add an #End If in the appropriate position.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Events (Visual Basic for Applications)

 Copy code hover
[image]

Events (Visual Basic for Applications)
Send feedback

In this section

  • Activate, Deactivate Events

  • Initialize Event

  • QueryClose Event

  • Resize Event

  • Terminate Event (Visual Basic for Applications)


Activate, Deactivate Events

 Copy code hover
[image]

Activate, Deactivate Events
Send feedback

The Activate event occurs when an object becomes the active window. The Deactivate event occurs when an object is no longer the active window.

Syntax

Private Sub object _Activate()

Private Sub object _Deactivate()

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

Remarks

An object can become active by using the Show method in code.

The Activate event can occur only when an object is visible. A UserForm loaded with Load isn't visible unless you use the Show method.

The Activate and Deactivate events occur only when you move the focus within an application. Moving the focus to or from an object in another application doesn't trigger either event.

The Deactivate event doesn't occur when unloading an object.

Example

The following code uses two UserForms: UserForm1 and UserForm2. Copy these procedures into the UserForm1 module, then add UserForm2. UserForm1's caption is created in its Activate event procedure. When the user clicks the client area of UserForm1, UserForm2 is loaded, and shown, triggering UserForm1's Deactivate event, changing their captions.

Copy code Copy code
' Activate event for UserForm1
Private Sub UserForm_Activate()
    UserForm1.Caption = "Click my client area"
End Sub

' Click event for UserForm1
Private Sub UserForm_Click()
    Load UserForm2
    UserForm2.StartUpPosition = 3
    UserForm2.Show
End Sub

' Deactivate event for UserForm1
Private Sub UserForm_Deactivate()
    UserForm1.Caption = "I just lost the focus!"
    UserForm2.Caption = "Focus just left UserForm1 and came to me"
End Sub


Initialize Event

 Copy code hover
[image]

Initialize Event
Send feedback

Occurs after an object is loaded, but before it's shown.

Syntax

Private Sub object _Initialize()

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

Remarks

The Initialize event is typically used to prepare an application or UserForm for use. Variables are assigned initial values, and controls may be moved or resized to accommodate initialization data.

Example

The following example assumes two UserForms in a program. In UserForm1's Initialize event, UserForm2 is loaded and shown. When the user clicks UserForm2, it is hidden and UserForm1 appears. When UserForm1 is clicked, UserForm2 is shown again.

Copy code Copy code
' This is the Initialize event procedure for UserForm1
Private Sub UserForm_Initialize()
    Load UserForm2
    UserForm2.Show
End Sub
' This is the Click event of UserForm2
Private Sub UserForm_Click()
    UserForm2.Hide
End Sub

' This is the click event for UserForm1
Private Sub UserForm_Click()
    UserForm2.Show
End Sub


QueryClose Event

 Copy code hover
[image]

QueryClose Event
Send feedback

Occurs before a UserForm closes.

Syntax

Private Sub UserForm_QueryClose( cancel As Integer, closemode As Integer)

The QueryClose event syntax has these parts:

Part | Description
cancel | An integer. Setting this argument to any value other than 0 stops the QueryClose event in all loaded user forms and prevents the UserForm and application from closing.
closemode | A value or constant indicating the cause of the QueryClose event.

Return Values

The closemode argument returns the following values:

Constant | Value | Description
vbFormControlMenu | 0 | The user has chosen the Close command from the Control menu on the UserForm.
vbFormCode | 1 | The Unload statement is invoked from code.
vbAppWindows | 2 | The current Windows operating environment session is ending.
vbAppTaskManager | 3 | The Windows Task Manager is closing the application.

These constants are listed in the Visual Basic for Applications object library in the Object Browser. Note that vbFormMDIForm is also specified in the Object Browser, but is not yet supported.

Remarks

This event is typically used to make sure there are no unfinished tasks in the user forms included in an application before that application closes. For example, if a user hasn't saved new data in any UserForm, the application can prompt the user to save the data.

When an application closes, you can use the QueryClose event procedure to set the Cancel property to True, stopping the closing process.

Example

The following code forces the user to click the UserForm's client area to close it. If the user tries to use the Close box in the title bar, the Cancel parameter is set to a nonzero value, preventing termination. However, if the user has clicked the client area, CloseMode has the value 1 and Unload Me is executed.

Copy code Copy code
Private Sub UserForm_Activate()
    UserForm1.Caption = "You must Click me to kill me!"
End Sub

Private Sub UserForm_Click()
  Unload Me
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    'Prevent user from closing with the Close box in the title bar.
    If CloseMode <> 1 Then Cancel = 1
    UserForm1.Caption = "The Close box won't work! Click me!"
End Sub


Resize Event

 Copy code hover
[image]

Resize Event
Send feedback

Occurs when a user form is resized.

Syntax

Private Sub UserForm_Resize()

Remarks

Use a Resize event procedure to move or resize controls when the parent UserForm is resized. You can also use this event procedure to recalculate variables or properties.

Example

The following example uses the Activate and Click events to illustrate triggering of the UserForm's Resize event. As the user clicks the client area of the form, it grows or shrinks and the new height is specified in the title bar. Note that the Tag property is used to store the UserForm's initial height.

Copy code Copy code
' Activate event for UserForm1
Private Sub UserForm_Activate()
    UserForm1.Caption = "Click me to make me taller!"
    Tag = Height    ' Save the initial height.
End Sub

' Click event for UserForm1
Private Sub UserForm_Click()
    Dim NewHeight As Single
    NewHeight = Height
    ' If the form is small, make it tall.
    If NewHeight = Val(Tag) Then
        Height = Val(Tag) * 2
    Else
    ' If the form is tall, make it small.
        Height = Val(Tag)
    End If
End Sub

' Resize event for UserForm1
Private Sub UserForm_Resize()
    UserForm1.Caption = "New Height: " & Height & "  " & "Click to resize me!"
End Sub


Terminate Event (Visual Basic for Applications)

 Copy code hover
[image]

Terminate Event (Visual Basic for Applications)
Send feedback

Occurs when all references to an instance of an object are removed from memory by setting all variables that refer to the object to Nothing or when the last reference to the object goes out of scope.

Syntax

Private Sub object _Terminate( )

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

Remarks

The Terminate event occurs after the object is unloaded. The Terminate event isn't triggered if the instances of the UserForm or class are removed from memory because the application terminated abnormally. For example, if your application invokes the End statement before removing all existing instances of the class or UserForm from memory, the Terminate event isn't triggered for that class or UserForm.

Copy code Copy code
Private Sub UserForm_Activate()
    UserForm1.Caption = "Click me to kill me!"
End Sub

Private Sub UserForm_Click()
  Unload Me
End Sub

Private Sub UserForm_Terminate()
    Dim Count As Integer
    For Count = 1 To 100
        Beep
    Next
End Sub

Example

The following event procedures cause a UserForm to beep for a few seconds after the user clicks the client area to dismiss the form.


Functions (Visual Basic for Applications)

 Copy code hover
[image]

Functions (Visual Basic for Applications)
Send feedback

In this section

  • Abs Function

  • Array Function

  • Asc Function

  • Atn Function

  • CallByName Function

  • Choose Function

  • Chr Function

  • Command Function

  • Conversion Functions

  • Cos Function

  • CreateObject Function

  • CurDir Function

  • CVErr Function

  • Date Function

  • DateAdd Function

  • DateDiff Function

  • DatePart Function

  • DateSerial Function

  • DateValue Function

  • Day Function

  • DDB Function

  • Derived Math Functions

  • Dir Function

  • DoEvents Function

  • Environ Function

  • EOF Function

  • Error Function

  • Exp Function

  • FileAttr Function

  • FileDateTime Function

  • FileLen Function

  • Filter Function

  • Format Function (Visual Basic for Applications)

  • FormatCurrency Function

  • FormatDateTime Function

  • FormatNumber Function

  • FormatPercent Function

  • FreeFile Function

  • FV Function

  • GetAllSettings Function

  • GetAttr Function

  • GetObject Function

  • GetSetting Function

  • Hex Function

  • Hour Function

  • IIf Function

  • IMEStatus Function

  • Input Function

  • InputBox Function

  • InStr Function

  • InStrRev Function

  • Int, Fix Functions

  • IPmt Function

  • IRR Function

  • IsArray Function

  • IsDate Function

  • IsEmpty Function

  • IsError Function

  • IsMissing Function

  • IsNull Function

  • IsNumeric Function

  • IsObject Function

  • Join Function

  • LBound Function

  • LCase Function

  • Left Function

  • Len Function

  • Loc Function

  • LOF Function

  • Log Function

  • LTrim, RTrim, and Trim Functions

  • MacID Function

  • MacScript Function

  • Math Functions

  • Mid Function

  • Minute Function

  • MIRR Function

  • Month Function

  • MonthName Function

  • MsgBox Function

  • Now Function

  • NPer Function

  • NPV Function

  • Oct Function

  • Partition Function

  • Pmt Function

  • PPmt Function

  • PV Function

  • QBColor Function

  • Rate Function

  • Replace Function

  • RGB Function

  • Right Function

  • Rnd Function

  • Round Function

  • Second Function

  • Seek Function

  • Sgn Function

  • Shell Function

  • Sin Function

  • SLN Function

  • Space Function

  • Spc Function

  • Split Function

  • Sqr Function

  • Str Function

  • StrComp Function

  • StrConv Function

  • String Function

  • StrReverse Function

  • Switch Function

  • SYD Function

  • Tab Function

  • Tan Function

  • Time Function

  • Timer Function

  • TimeSerial Function

  • TimeValue Function

  • Type Conversion Functions

  • TypeName Function

  • UBound Function

  • UCase Function

  • Val Function

  • VarType Function

  • Weekday Function

  • WeekdayName Function

  • Year Function


Abs Function

 Copy code hover
[image]

Abs Function
Send feedback

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

Syntax

Abs( number )

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

Remarks

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

Example

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

VBA Copy code Copy code
Dim MyNumber
MyNumber = Abs(50.3)    ' Returns 50.3.
MyNumber = Abs(-50.3)    ' Returns 50.3.


Array Function

 Copy code hover
[image]

Array Function
Send feedback

Returns a Variant containing an array.

Syntax

Array( arglist )

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

Remarks

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

VBA Copy code Copy code
Dim A As Variant
A = Array(10,20,30)
B = A(2)

The lower bound of an array created using the Array function is determined by the lower bound specified with the Option Base statement, unless Array is qualified with the name of the type library (for example VBA.Array). If qualified with the type-library name, Array is unaffected by Option Base.

Note Note

A Variant that is not declared as an array can still contain an array. A Variant variable can contain an array of any type, except fixed-length strings and user-defined types. Although a Variant containing an array is conceptually different from an array whose elements are of type Variant, the array elements are accessed in the same way.

Example

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

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


Asc Function

 Copy code hover
[image]

Asc Function
Send feedback

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

Syntax

Asc( string )

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

Remarks

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

Note Note

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

Visual Basic for the Macintosh does not support Unicode strings. Therefore, AscW(n) cannot return all Unicode characters for n values in the range of 128 - 65,535, as it does in the Windows environment. Instead, AscW(n) attempts a "best guess" for Unicode values n greater than 127. Therefore, you should not use AscW in the Macintosh environment.

Example

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

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


Atn Function

 Copy code hover
[image]

Atn Function
Send feedback

Returns a Double specifying the arctangent of a number.

Syntax

Atn( number )

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

Remarks

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

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

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

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

Example

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

Copy code Copy code
Dim IntVar, StrVar, DateVar, MyCheck
' Initialize variables.
IntVar = 459: StrVar = "Hello World": DateVar = #2/12/69#
MyCheck = VarType(IntVar)    ' Returns 2.
MyCheck = VarType(DateVar)    ' Returns 7.
MyCheck = VarType(StrVar)    ' Returns 8.


CallByName Function

 Copy code hover
[image]

CallByName Function
Send feedback

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

Syntax

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

The CallByName function syntax has these named arguments:

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

Remarks

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

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

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

Example

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

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

VBA Copy code Copy code
Option Explicit

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

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


Choose Function

 Copy code hover
[image]

Choose Function
Send feedback

Selects and returns a value from a list of arguments.

Syntax

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

The Choose function syntax has these parts:

Part | Description
index | Required. Numeric expression or field that results in a value between 1 and the number of available choices.
choice | Required. Variant expression containing one of the possible choices.

Remarks

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

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

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

The Choose function returns a Null if index is less than 1 or greater than the number of choices listed.

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

Example

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

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


Chr Function

 Copy code hover
[image]

Chr Function
Send feedback

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

Syntax

Chr( charcode )

The required charcode argument is a Long that identifies a character.

Remarks

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

Note Note

The ChrB function is used with byte data contained in a String. Instead of returning a character, which may be one or two bytes, ChrB always returns a single byte. The ChrW function returns a String containing the Unicode character except on platforms where Unicode is not supported, in which case, the behavior is identical to the Chr function.
Note Note

Visual Basic for the Macintosh does not support Unicode strings. Therefore, ChrW(n) cannot return all Unicode characters for n values in the range of 128 - 65,535, as it does in the Windows environment. Instead, ChrW(n) attempts a "best guess" for Unicode values n greater than 127. Therefore, you should not use ChrW in the Macintosh environment.

Example

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

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


Command Function

 Copy code hover
[image]

Command Function
Send feedback

Returns the argument portion of the command line used to launch Microsoft Visual Basic or an executable program developed with Visual Basic. The Visual Basic Command function is not available in Microsoft Office applications.

Syntax

Command

Remarks

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

Copy code Copy code
VB /cmd cmdlineargs

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

Copy code Copy code
MyApp cmdlineargs

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

Example

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

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


Conversion Functions

 Copy code hover
[image]

Conversion Functions
Send feedback

Asc Function

CBool Function

CByte Function

CCur Function

CDate Function

CDec Function

CDbl Function

Chr Function

CInt Function

CLng Function

CLngLng Function

CLngPtr Function

CSng Function

CStr Function

CVar Function

CVErr Function

Format Function

Hex Function

Oct Function

Str Function

Val Function


Cos Function

 Copy code hover
[image]

Cos Function
Send feedback

Returns a Double specifying the cosine of an angle.

Syntax

Cos( number )

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

Remarks

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

The result lies in the range -1 to 1.

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

Example

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

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


CreateObject Function

 Copy code hover
[image]

CreateObject Function
Send feedback

Creates and returns a reference to an ActiveX object.

Syntax

CreateObject( class,[servername] )

The CreateObject function syntax has these parts:

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

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

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

Remarks

Every application that supports Automation provides at least one type of object. For example, a word processing application may provide an Application object, a Document object, and a Toolbar object.

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

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

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

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

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

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

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

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

VBA Copy code Copy code
Call MySub (CreateObject("Excel.Application"))

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

Note Note

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

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

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

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

Note Note

Use CreateObject when there is no current instance of the object. If an instance of the object is already running, a new instance is started, and an object of the specified type is created. To use the current instance, or to start the application and have it load a file, use the GetObject function.

If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed.

Example

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

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

Set xlApp = CreateObject("excel.application")
    ' You may have to set Visible property to True
    ' if you want to see the application.
xlApp.Visible = True
    ' Use xlApp to access Microsoft Excel's
    ' other objects.


CurDir Function

 Copy code hover
[image]

CurDir Function
Send feedback

Returns a Variant (String) representing the current path.

Syntax

CurDir[(drive)]

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

Example

This example uses the CurDir function to return the current path. On the Macintosh, drive specifications given to CurDir are ignored. The default drive name is "HD" and portions of the pathname are separated by colons instead of backslashes. Similarly, you would specify Macintosh folders instead of \Windows.

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


CVErr Function

 Copy code hover
[image]

CVErr Function
Send feedback

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

Syntax

CVErr( errornumber )

The required errornumber argument is any valid error number.

Remarks

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

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

Example

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

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


Date Function

 Copy code hover
[image]

Date Function
Send feedback

Returns a Variant (Date) containing the current system date.

Syntax

Date

Remarks

To set the system date, use the Date statement.

Date, and if the calendar is Gregorian, Date$ behavior is unchanged by the Calendar property setting. If the calendar is Hijri, Date$ returns a 10-character string of the form mm-dd-yyyy, where mm (01-12), dd (01-30) and yyyy (1400-1523) are the Hijri month, day and year. The equivalent Gregorian range is Jan 1, 1980 through Dec 31, 2099.

Example

This example uses the Date function to return the current system date.

Copy code Copy code
Dim MyDate
MyDate = Date    ' MyDate contains the current system date.


DateAdd Function

 Copy code hover
[image]

DateAdd Function
Send feedback

Returns a Variant (Date) containing a date to which a specified time interval has been added.

Syntax

DateAdd(interval, number, date)

The DateAdd function syntax has these named arguments:

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

Settings

The interval argument has these settings:

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

Remarks

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

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

Note Note

When you use the "w" interval (which includes all the days of the week, Sunday through Saturday) to add days to a date, the DateAdd function adds the total number of days that you specified to the date, instead of adding just the number of workdays (Monday through Friday) to the date, as you might expect.

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

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

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

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

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

Note Note

The format of the return value for DateAdd is determined by Control Panel settings, not by the format that is passed in date argument.
Note Note

For date, if the Calendar property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri. If month values are names, the name must be consistent with the current Calendar property setting. To minimize the possibility of month names conflicting with the current Calendar property setting, enter numeric month values (Short Date format).

Example

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

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


DateDiff Function

 Copy code hover
[image]

DateDiff Function
Send feedback

Returns a Variant (Long) specifying the number of time intervals between two specified dates.

Syntax

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

The DateDiff function syntax has these named arguments:

Part | Description
interval | Required. String expression that is the interval of time you use to calculate the difference between date1 and date2.
date1 , date2 | Required; Variant (Date). Two dates you want to use in the calculation.
firstdayofweek | Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed.
firstweekofyear | Optional. A constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs.

Settings

The interval argument has these settings:

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

The firstdayofweek argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use the NLS API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday
Constant | Value | Description
vbUseSystem | 0 | Use the NLS API setting.
vbFirstJan1 | 1 | Start with week in which January 1 occurs (default).
vbFirstFourDays | 2 | Start with the first week that has at least four days in the new year.
vbFirstFullWeek | 3 | Start with first full week of the year.

Remarks

You can use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today and the end of the year.

To calculate the number of days between date1 and date2, you can use either Day of year ("y") or Day ("d"). When interval is Weekday ("w"), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1. If interval is Week ("ww"), however, the DateDiff function returns the number of calendar weeks between the two dates. It counts the number of Sundays between date1 and date2. DateDiff counts date2 if it falls on a Sunday; but it doesn't count date1, even if it does fall on a Sunday.

If date1 refers to a later point in time than date2, the DateDiff function returns a negative number.

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

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

When comparing December 31 to January 1 of the immediately succeeding year, DateDiff for Year ("yyyy") returns 1 even though only a day has elapsed.

Note Note

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

Example

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

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


DatePart Function

 Copy code hover
[image]

DatePart Function
Send feedback

Returns a Variant (Integer) containing the specified part of a given date.

Syntax

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

The DatePart function syntax has these named arguments:

Part | Description
interval | Required. String expression that is the interval of time you want to return.
date | Required. Variant (Date) value that you want to evaluate.
firstdayofweek | Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed.
firstweekofyear | Optional. A constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs.

Settings

The interval argument has these settings:

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

The firstdayofweek argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use the NLS API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

The firstweekofyear argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use the NLS API setting.
vbFirstJan1 | 1 | Start with week in which January 1 occurs (default).
vbFirstFourDays | 2 | Start with the first week that has at least four days in the new year.
vbFirstFullWeek | 3 | Start with first full week of the year.

Remarks

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

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

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

Note Note

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

The returned date part is in the time period units of the current Arabic calendar. For example, if the current calendar is Hijri and the date part to be returned is the year, the year value is a Hijri year.

Example

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

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


DateSerial Function

 Copy code hover
[image]

DateSerial Function
Send feedback

Returns a Variant (Date) for a specified year, month, and day.

Syntax

DateSerial(year, month, day)

The DateSerial function syntax has these named arguments:

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

Remarks

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

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

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

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

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

Note Note

For year, month, and day, if the Calendar property setting is Gregorian, the supplied value is assumed to be Gregorian. If the Calendar property setting is Hijri, the supplied value is assumed to be Hijri.

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

Example

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

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


DateValue Function

 Copy code hover
[image]

DateValue Function
Send feedback

Returns a Variant (Date).

Syntax

DateValue( date )

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

Remarks

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

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

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

Note Note

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

Example

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

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


Day Function

 Copy code hover
[image]

Day Function
Send feedback

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

Syntax

Day( date )

The required date argument is any Variant, numeric expression, string expression, or any combination, that can represent a date. If date contains Null, Null is returned.

Note Note

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

Example

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

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


DDB Function

 Copy code hover
[image]

DDB Function
Send feedback

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

Syntax

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

The DDB function has these named arguments:

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

Remarks

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

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

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

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

Example

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

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


Derived Math Functions

 Copy code hover
[image]

Derived Math Functions
Send feedback

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

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


Dir Function

 Copy code hover
[image]

Dir Function
Send feedback

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

Syntax

Dir[(pathname[, attributes])]

The Dir function syntax has these parts:

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

Settings

The attributes argument settings are:

Constant | Value | Description
vbNormal | 0 | (Default) Specifies files with no attributes.
vbReadOnly | 1 | Specifies read-only files in addition to files with no attributes.
vbHidden | 2 | Specifies hidden files in addition to files with no attributes.
VbSystem | 4 | Specifies system files in addition to files with no attributes. Not available on the Macintosh.
vbVolume | 8 | Specifies volume label; if any other attributed is specified, vbVolume is ignored. Not available on the Macintosh.
vbDirectory | 16 | Specifies directories or folders in addition to files with no attributes.
vbAlias | 64 | Specified file name is an alias. Available only on the Macintosh.
Note Note

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

Remarks

In Microsoft Windows, Dir supports the use of multiple character (*) and single character (?) wildcards to specify multiple files. On the Macintosh, these characters are treated as valid file name characters and can't be used as wildcards to specify multiple files.

Since the Macintosh doesn't support the wildcards, use the file type to identify groups of files. You can use the MacID function to specify file type instead of using the file names. For example, the following statement returns the name of the first TEXT file in the current folder:

Copy code Copy code
Dir("SomePath", MacID("TEXT"))

To iterate over all files in a folder, specify an empty string:

Copy code Copy code
Dir("")

If you use the MacID function with Dir in Microsoft Windows, an error occurs.

Any attribute value greater than 256 is considered a MacID value.

You must specify pathname the first time you call the Dir function, or an error occurs. If you also specify file attributes, pathname must be included.

Dir returns the first file name that matches pathname. To get any additional file names that match pathname, call Dir again with no arguments. When no more file names match, Dir returns a zero-length string (""). Once a zero-length string is returned, you must specify pathname in subsequent calls or an error occurs. You can change to a new pathname without retrieving all of the file names that match the current pathname. However, you can't call the Dir function recursively. Calling Dir with the vbDirectory attribute does not continually return subdirectories.

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


DoEvents Function

 Copy code hover
[image]

DoEvents Function
Send feedback

Yields execution so that the operating system can process other events.

Syntax

DoEvents( )

Remarks

The DoEvents function returns an Integer representing the number of open forms in stand-alone versions of Visual Basic, such as Visual Basic, Professional Edition. DoEvents returns zero in all other applications.

DoEvents passes control to the operating system. Control is returned after the operating system has finished processing the events in its queue and all keys in the SendKeys queue have been sent.

DoEvents is most useful for simple things like allowing a user to cancel a process after it has started, for example a search for a file. For long-running processes, yielding the processor is better accomplished by using a Timer or delegating the task to an ActiveX EXE component. In the latter case, the task can continue completely independent of your application, and the operating system takes case of multitasking and time slicing.

Any time you temporarily yield the processor within an event procedure, make sure the procedure is not executed again from a different part of your code before the first 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.

Example

This example uses the DoEvents function to cause execution to yield to the operating system once every 1000 iterations of the loop. DoEvents returns the number of open Visual Basic forms, but only when the host application is Visual Basic.

Copy code Copy code
' Create a variable to hold number of Visual Basic forms loaded
' and visible.
Dim I, OpenForms
For I = 1 To 150000    ' Start loop.
    If I Mod 1000 = 0 Then     ' If loop has repeated 1000 times.
        OpenForms = DoEvents    ' Yield to operating system.
    End If
Next I    ' Increment loop counter.


Environ Function

 Copy code hover
[image]

Environ Function
Send feedback

Returns the String associated with an operating system environment variable. Not available on the Macintosh

Syntax

Environ({envstring | number})

The Environ function syntax has these named arguments:

Part | Description
envstring | Optional. String expression containing the name of an environment variable.
number | Optional. Numeric expression corresponding to the numeric order of the environment string in the environment-string table. The number argument can be any numeric expression, but is rounded to a whole number before it is evaluated.

Remarks

If envstring can't be found in the environment-string table, a zero-length string ("") is returned. Otherwise, Environ returns the text assigned to the specified envstring; that is, the text following the equal sign (=) in the environment-string table for that environment variable.

If you specify number, the string occupying that numeric position in the environment-string table is returned. In this case, Environ returns all of the text, including envstring. If there is no environment string in the specified position, Environ returns a zero-length string.

Example

This example uses the Environ function to supply the entry number and length of the PATH statement from the environment-string table. Not available on the Macintosh.

Copy code Copy code
Dim EnvString, Indx, Msg, PathLen    ' Declare variables.
Indx = 1    ' Initialize index to 1.
Do
    EnvString = Environ(Indx)    ' Get environment
                ' variable.
    If Left(EnvString, 5) = "PATH=" Then    ' Check PATH entry.
        PathLen = Len(Environ("PATH"))    ' Get length.
        Msg = "PATH entry = " & Indx & " and length = " & PathLen
        Exit Do
    Else
        Indx = Indx + 1    ' Not PATH entry,
    End If    ' so increment.
Loop Until EnvString = ""
If PathLen > 0 Then
    MsgBox Msg    ' Display message.
Else
    MsgBox "No PATH environment variable exists."
End If


EOF Function

 Copy code hover
[image]

EOF Function
Send feedback

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

Syntax

EOF( filenumber )

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

Remarks

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

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

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

Example

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

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


Error Function

 Copy code hover
[image]

Error Function
Send feedback

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

Syntax

Error[(errornumber)]

The optional errornumber argument can be any valid error number. If errornumber is a valid error number, but is not defined, Error returns the string "Application-defined or object-defined error." If errornumber is not valid, an error occurs. If errornumber is omitted, the message corresponding to the most recent run-time error is returned. If no run-time error has occurred, or errornumber is 0, Error returns a zero-length string ("").

Remarks

Examine the property settings of the Err object to identify the most recent run-time error. The return value of the Error function corresponds to the Description property of the Err object.

Example

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

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


Exp Function

 Copy code hover
[image]

Exp Function
Send feedback

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

Syntax

Exp( number )

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

Remarks

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

Note Note

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

Example

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

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


FileAttr Function

 Copy code hover
[image]

FileAttr Function
Send feedback

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

Syntax

FileAttr(filenumber, returntype)

The FileAttr function syntax has these named arguments:

Part | Description
filenumber | Required; Integer. Any valid file number.
returntype | Required; Integer. Number indicating the type of information to return. Specify 1 to return a value indicating the file mode. On 16-bit systems only, specify 2 to retrieve an operating system file handle. Returntype 2 is not supported in 32-bit systems and causes an error.

Return Values

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

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

Example

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

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


FileDateTime Function

 Copy code hover
[image]

FileDateTime Function
Send feedback

Returns a Variant (Date) that indicates the date and time when a file was created or last modified.

Syntax

FileDateTime( pathname )

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

Example

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

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


FileLen Function

 Copy code hover
[image]

FileLen Function
Send feedback

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

Syntax

FileLen( pathname )

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

Remarks

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

Note Note

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

Example

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

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


Filter Function

 Copy code hover
[image]

Filter Function
Send feedback

Description

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

Syntax

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

The Filter function syntax has these named argument:

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

Settings

The compare argument can have the following values:

Constant | Value | Description
vbUseCompareOption | -1 | Performs a comparison using the setting of the Option Compare statement.
vbBinaryCompare | 0 | Performs a binary comparison.
vbTextCompare | 1 | Performs a textual comparison.
vbDatabaseCompare | 2 | Microsoft Access only. Performs a comparison based on information in your database.

Remarks

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

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


Format Function (Visual Basic for Applications)

 Copy code hover
[image]

Format Function (Visual Basic for Applications)
Send feedback

Description

Returns a Variant (String) containing an expression formatted according to instructions contained in a format expression.

Syntax

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

The Format function syntax has these parts:

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

Settings

The firstdayofweek argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use NLS API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

The firstweekofyear argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use NLS API setting.
vbFirstJan1 | 1 | Start with week in which January 1 occurs (default).
vbFirstFourDays | 2 | Start with the first week that has at least four days in the year.
vbFirstFullWeek | 3 | Start with the first full week of the year.

Remarks

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

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

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

Note Note

If the Calendar property setting is Gregorian and format specifies date formatting, the supplied expression must be Gregorian. If the Visual Basic Calendar property setting is Hijri, the supplied expression must be Hijri.

If the calendar is Gregorian, the meaning of format expression symbols is unchanged. If the calendar is Hijri, all date format symbols (for example, dddd, mmmm, yyyy) have the same meaning but apply to the Hijri calendar. Format symbols remain in English; symbols that result in text display (for example, AM and PM) display the string (English or Arabic) associated with that symbol. The range of certain symbols changes when the calendar is Hijri.

Symbol | Range
d | 1-30
dd | 1-30
ww | 1-51
mmm | Displays full month names (Hijri month names have no abbreviations).
y | 1-355
yyyy | 100-9666

Example

This example shows various uses of the Format function to format values using both named formats and user-defined formats. For the date separator (/), time separator (:), and AM/ PM literal, the actual formatted output displayed by your system depends on the locale settings on which the code is running. When times and dates are displayed in the development environment, the short time format and short date format of the code locale are used. When displayed by running code, the short time format and short date format of the system locale are used, which may differ from the code locale. For this example, English/U.S. is assumed. MyTime and MyDate are displayed in the development environment using current system short time setting and short date setting.

VBA Copy code Copy code
Dim MyTime, MyDate, MyStr
MyTime = #17:04:23#
MyDate = #January 27, 1993#

' Returns current system time in the system-defined long time format.
MyStr = Format(Time, "Long Time")

' Returns current system date in the system-defined long date format.
MyStr = Format(Date, "Long Date")

MyStr = Format(MyTime, "h:m:s")    ' Returns "17:4:23".
MyStr = Format(MyTime, "hh:mm:ss AMPM")    ' Returns "05:04:23 PM".
MyStr = Format(MyDate, "dddd, mmm d yyyy")    ' Returns "Wednesday,
    ' Jan 27 1993".
' If format is not supplied, a string is returned.
MyStr = Format(23)    ' Returns "23".

' User-defined formats.
MyStr = Format(5459.4, "##,##0.00")    ' Returns "5,459.40".
MyStr = Format(334.9, "###0.00")    ' Returns "334.90".
MyStr = Format(5, "0.00%")    ' Returns "500.00%".
MyStr = Format("HELLO", "<")    ' Returns "hello".
MyStr = Format("This is it", ">")    ' Returns "THIS IS IT".

Different Formats for Different Numeric Values (Format Function)

A user-defined format expression for numbers can have from one to four sections separated by semicolons. If the format argument contains one of the named numeric formats, only one section is allowed.

If you use | The result is
One section only | The format expression applies to all values.
Two sections | The first section applies to positive values and zeros, the second to negative values.
Three sections | The first section applies to positive values, the second to negative values, and the third to zeros.
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.

VBA Copy code Copy code
"$#,##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.

VBA Copy code Copy code
"$#,##0;;\Z\e\r\o"

Different Formats for Different String Values (Format Function)

A format expression for strings can have one section or two sections separated by a semicolon (;).

If you use | The result is
One section only | The format applies to all string data.
Two sections | The first section applies to string data, the second to Null values and zero-length strings ("").

Named Date/Time Formats (Format Function)

The following table identifies the predefined date and time format names:

Format Name | Description
General Date | Display a date and/or time. For real numbers, display a date and time, for example, 4/3/93 05:34 PM.If there is no fractional part, display only a date, for example, 4/3/93. If there is no integer part, display time only, for example, 05:34 PM. Date display is determined by your system settings.
Long Date | Display a date according to your system's long date format.
Medium Date | Display a date using the medium date format appropriate for the language version of the host application.
Short Date | Display a date using your system's short date format.
Long Time | Display a time using your system's long time format; includes hours, minutes, seconds.
Medium Time | Display time in 12-hour format using hours and minutes and the AM/PM designator.
Short Time | Display a time using the 24-hour format, for example, 17:45.

Named Numeric Formats (Format Function)

The following table identifies the predefined numeric format names:

Format name | Description
General Number | Display number with no thousand separator.
Currency | Display number with thousand separator, if appropriate; display two digits to the right of the decimal separator. Output is based on system locale settings.
Fixed | Display at least one digit to the left and two digits to the right of the decimal separator.
Standard | Display number with thousand separator, at least one digit to the left and two digits to the right of the decimal separator.
Percent | Display number multiplied by 100 with a percent sign (%) appended to the right; always display two digits to the right of the decimal separator.
Scientific | Use standard scientific notation.
Yes/No | Display No if number is 0; otherwise, display Yes.
True/False | Display False if number is 0; otherwise, display True.
On/Off | Display Off if number is 0; otherwise, display On.

User-Defined String Formats (Format Function)

You can use any of the following characters to create a format expression for strings:

Character | Description
@ | Character placeholder. Display a character or a space. If the string has a character in the position where the at symbol (@) appears in the format string, display it; otherwise, display a space in that position. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string.
& | Character placeholder. Display a character or nothing. If the string has a character in the position where the ampersand (&) appears, display it; otherwise, display nothing. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string.
< | Force lowercase. Display all characters in lowercase format.
> | Force uppercase. Display all characters in uppercase format.
! | Force left to right fill of placeholders. The default is to fill placeholders from right to left.

User-Defined Date/Time Formats (Format Function)

The following table identifies characters you can use to create user-defined date/time formats:

Character | Description
(:) | Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.
(/) | Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.
c | Display the date as ddddd and display the time as ttttt, in that order. Display only date information if there is no fractional part to the date serial number; display only time information if there is no integer portion.
d | Display the day as a number without a leading zero (1 - 31).
dd | Display the day as a number with a leading zero (01 - 31).
ddd | Display the day as an abbreviation (Sun - Sat).
dddd | Display the day as a full name (Sunday - Saturday).
ddddd | Display the date as a complete date (including day, month, and year), formatted according to your system's short date format setting. The default short date format is m/d/yy.
dddddd | Display a date serial number as a complete date (including day, month, and year) formatted according to the long date setting recognized by your system. The default long date format is mmmm dd, yyyy.
aaaa | The same as dddd, only it's the localized version of the string.
w | Display the day of the week as a number (1 for Sunday through 7 for Saturday).
ww | Display the week of the year as a number (1 - 54).
m | Display the month as a number without a leading zero (1 - 12). If m immediately follows h or hh, the minute rather than the month is displayed.
mm | Display the month as a number with a leading zero (01 - 12). If m immediately follows h or hh, the minute rather than the month is displayed.
mmm | Display the month as an abbreviation (Jan - Dec).
mmmm | Display the month as a full month name (January - December).
oooo | The same as mmmm, only it's the localized version of the string.
q | Display the quarter of the year as a number (1 - 4).
y | Display the day of the year as a number (1 - 366).
yy | Display the year as a 2-digit number (00 - 99).
yyyy | Display the year as a 4-digit number (100 - 9999).
h | Display the hour as a number without leading zeros (0 - 23).
Hh | Display the hour as a number with leading zeros (00 - 23).
N | Display the minute as a number without leading zeros (0 - 59).
Nn | Display the minute as a number with leading zeros (00 - 59).
S | Display the second as a number without leading zeros (0 - 59).
Ss | Display the second as a number with leading zeros (00 - 59).
t t t t t | Display a time as a complete time (including hour, minute, and second), formatted using the time separator defined by the time format recognized by your system. A leading zero is displayed if the leading zero option is selected and the time is before 10:00 A.M. or P.M. The default time format is h:mm:ss.
AM/PM | Use the 12-hour clock and display an uppercase AM with any hour before noon; display an uppercase PM with any hour between noon and 11:59 P.M.
am/pm | Use the 12-hour clock and display a lowercase AM with any hour before noon; display a lowercase PM with any hour between noon and 11:59 P.M.
A/P | Use the 12-hour clock and display an uppercase A with any hour before noon; display an uppercase P with any hour between noon and 11:59 P.M.
a/p | Use the 12-hour clock and display a lowercase A with any hour before noon; display a lowercase P with any hour between noon and 11:59 P.M.
AMPM | Use the 12-hour clock and display the AM string literal as defined by your system with any hour before noon; display the PM string literal as defined by your system with any hour between noon and 11:59 P.M. AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as defined by your system settings. The default format is AM/PM.

User-Defined Numeric Formats (Format Function)

The following table identifies characters you can use to create user-defined number formats:

Character

Description

None

Display the number with no formatting.

(0)

Digit placeholder. Display a digit or a zero. If the expression has a digit in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position.

If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, round the number to as many decimal places as there are zeros. If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, display the extra digits without modification.

(#)

Digit placeholder. Display a digit or nothing. If the expression has a digit in the position where the # appears in the format string, display it; otherwise, display nothing in that position.

This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren't displayed if the number has the same or fewer digits than there are # characters on either side of the decimal separator in the format expression.

(.)

Decimal placeholder. In some locales, a comma is used as the decimal separator. The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator. If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator. To display a leading zero displayed with fractional numbers, use 0 as the first digit placeholder to the left of the decimal separator. The actual character used as a decimal placeholder in the formatted output depends on the Number Format recognized by your system.

(%)

Percentage placeholder. The expression is multiplied by 100. The percent character (%) is inserted in the position where it appears in the format string.

(,)

Thousand separator. In some locales, a period is used as a thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #). Two adjacent thousand separators or a thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) means "scale the number by dividing it by 1000, rounding as needed." For example, you can use the format string "##0,," to represent 100 million as 100. Numbers smaller than 1 million are displayed as 0. Two adjacent thousand separators in any position other than immediately to the left of the decimal separator are treated simply as specifying the use of a thousand separator. The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your system.

(:)

Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.

(/)

Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.

(E- E+ e- e+)

Scientific format. If the format expression contains at least one digit placeholder (0 or #) to the 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.

- + $ ( )

Display a literal character. To display a character other than one of those listed, precede it with a backslash (\) or enclose it in double quotation marks (" ").

(\)

Display the next character in the format string. To display a character that has special meaning as a literal character, precede it with a backslash (\). The backslash itself isn't displayed. Using a backslash is the same as enclosing the next character in double quotation marks. To display a backslash, use two backslashes (\\).

Examples of characters that can't be displayed as literal characters are the date-formatting and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, / and :), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <, >, and !).

("ABC")

Display the string inside the double quotation marks (" "). To include a string in format from within code, you must use Chr(34) to enclose the text (34 is the character code for a quotation mark (")).


FormatCurrency Function

 Copy code hover
[image]

FormatCurrency Function
Send feedback

Description

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

Syntax

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

The FormatCurrency function syntax has these parts:

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

Settings

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

Constant | Value | Description
vbTrue | -1 | True
vbFalse | 0 | False
vbUseDefault | -2 | Use the setting from the computer's regional settings.

Remarks

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

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

Note Note

All settings information comes from the Regional Settings Currency tab, except leading zero which comes from the Number tab.


FormatDateTime Function

 Copy code hover
[image]

FormatDateTime Function
Send feedback

Description

Returns an expression formatted as a date or time.

Syntax

FormatDateTime( Date[,NamedFormat])

The FormatDateTime function syntax has these parts:

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

Settings

The NamedFormat argument has the following settings:

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


FormatNumber Function

 Copy code hover
[image]

FormatNumber Function
Send feedback

Description

Returns an expression formatted as a number.

Syntax

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

The FormatNumber function syntax has these parts:

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

Settings

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

Constant | Value | Description
vbTrue | -1 | True
vbFalse | 0 | False
vbUseDefault | -2 | Use the setting from the computer's regional settings.

Remarks

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

Note Note

All settings information comes from the Regional Settings Number tab.


FormatPercent Function

 Copy code hover
[image]

FormatPercent Function
Send feedback

Description

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

Syntax

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

The FormatPercent function syntax has these parts:

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

Settings

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

Constant | Value | Description
vbTrue | -1 | True
vbFalse | 0 | False
vbUseDefault | -2 | Use the setting from the computer's regional settings.

Remarks

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

Note Note

All settings information comes from the Regional Settings Number tab.


FreeFile Function

 Copy code hover
[image]

FreeFile Function
Send feedback

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

Syntax

FreeFile[(rangenumber)]

The optional rangenumber argument is a Variant that specifies the range from which the next free file number is to be returned. Specify a 0 (default) to return a file number in the range 1 - 255, inclusive. Specify a 1 to return a file number in the range 256 - 511.

Remarks

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

Example

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

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


FV Function

 Copy code hover
[image]

FV Function
Send feedback

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

Syntax

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

The FV function has these named arguments:

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

Remarks

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

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

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

Example

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

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


GetAllSettings Function

 Copy code hover
[image]

GetAllSettings Function
Send feedback

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

Syntax

GetAllSettings(appname, section)

The GetAllSettings function syntax has these named arguments:

Part | Description
appname | Required. String expression containing the name of the application or project whose key settings are requested. On the Macintosh, this is the filename of the initialization file in the Preferences folder in the System folder.
section | Required. String expression containing the name of the section whose key settings are requested. GetAllSettings returns a Variant whose contents is a two-dimensional array of strings containing all the key settings in the specified section and their corresponding values.

Remarks

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

Example

This example first uses the SaveSetting statement to make entries in the Windows registry for the application specified as appname, then uses the GetAllSettings function to display the settings. Note that application names and section names can't be retrieved with GetAllSettings. Finally, the DeleteSetting statement removes the application's entries.

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


GetAttr Function

 Copy code hover
[image]

GetAttr Function
Send feedback

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

Syntax

GetAttr( pathname )

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

Return Values

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

Constant | Value | Description
vbNormal | 0 | Normal.
vbReadOnly | 1 | Read-only.
vbHidden | 2 | Hidden.
vbSystem | 4 | System file. Not available on the Macintosh.
vbDirectory | 16 | Directory or folder.
vbArchive | 32 | File has changed since last backup. Not available on the Macintosh.
vbAlias | 64 | Specified file name is an alias. Available only on the Macintosh.
Note Note

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

Remarks

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

Copy code Copy code
Result = GetAttr(FName) And vbArchive

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

Example

This example uses the GetAttr function to determine the attributes of a file and directory or folder. On the Macintosh, only the constants vbNormal, vbReadOnly, vbHidden and vbAlias are available.

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

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

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

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

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


GetObject Function

 Copy code hover
[image]

GetObject Function
Send feedback

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

Syntax

GetObject([pathname] [, class])

The GetObject function syntax has these named arguments:

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

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

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

Remarks

Use the GetObject function to access an ActiveX object from a file and assign the object to an object variable. Use the Set statement to assign the object returned by GetObject to the object variable. For example:

VBA Copy code Copy code
Dim CADObject As Object
Set CADObject = GetObject("C:\CAD\SCHEMA.CAD")

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

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

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

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

VBA Copy code Copy code
Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

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

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

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

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

VBA Copy code Copy code
MyObject.Line 9, 90
MyObject.InsertText 9, 100, "Hello, world."
MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW"
Note Note

Use the GetObject function when there is a current instance of the object or if you want to create the object with a file already loaded. If there is no current instance, and you don't want the object started with a file loaded, use the CreateObject function.

If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed. With a single-instance object, GetObject always returns the same instance when called with the zero-length string ("") syntax, and it causes an error if the pathname argument is omitted. You can't use GetObject to obtain a reference to a class created with Visual Basic.

Example

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

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

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

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

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

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

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

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

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

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


GetSetting Function

 Copy code hover
[image]

GetSetting Function
Send feedback

Returns a key setting value from an application's entry in the Windows registry or (on the Macintosh) information in the application's initialization file.

Syntax

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

The GetSetting function syntax has these named arguments:

Part | Description
appname | Required. String expression containing the name of the application or project whose key setting is requested. On the Macintosh, this is the filename of the initialization file in the Preferences folder in the System folder.
section | Required. String expression containing the name of the section where the key setting is found.
key | Required. String expression containing the name of the key setting to return.
default | Optional. Expression containing the value to return if no value is set in the key setting. If omitted, default is assumed to be a zero-length string ("").

Remarks

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

Example

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

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

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

DeleteSetting "MyApp", "Startup"


Hex Function

 Copy code hover
[image]

Hex Function
Send feedback

Returns a String representing the hexadecimal value of a number.

Syntax

Hex(number)

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

Remarks

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

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

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

Example

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

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


Hour Function

 Copy code hover
[image]

Hour Function
Send feedback

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

Syntax

Hour( time )

The required time argument is any Variant, numeric expression, string expression, or any combination, that can represent a time. If time contains Null, Null is returned.

Example

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

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


IIf Function

 Copy code hover
[image]

IIf Function
Send feedback

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

Syntax

IIf(expr, truepart, falsepart)

The IIf function syntax has these named arguments:

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

Remarks

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

Example

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

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


IMEStatus Function

 Copy code hover
[image]

IMEStatus Function
Send feedback

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

Syntax

IMEStatus

Return Values

The return values for the Japanese locale are as follows:

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

The return values for the Korean locale are as follows:

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

The return values for the Chinese locale are as follows:

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


Input Function

 Copy code hover
[image]

Input Function
Send feedback

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

Syntax

Input( number, [#]filenumber)

The Input function syntax has these parts:

Part | Description
number | Required. Any valid numeric expression specifying the number of characters to return.
filenumber | Required. Any valid file number.

Remarks

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

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

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

Note Note

Use the InputB function for byte data contained within text files. With InputB, number specifies the number of bytes to return rather than the number of characters to return.

Example

This example uses the Input function to read one character at a time from a file and print it to the Immediate window. This example assumes that TESTFILE is a text file with a few lines of sample data.

Copy code Copy code
Dim MyChar
Open "TESTFILE" For Input As #1    ' Open file.
Do While Not EOF(1)    ' Loop until end of file.
    MyChar = Input(1, #1)    ' Get one character.
    Debug.Print MyChar    ' Print to the Immediate window.
Loop
Close #1    ' Close file.


InputBox Function

 Copy code hover
[image]

InputBox Function
Send feedback

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

Syntax

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

The InputBox function syntax has these named arguments:

Part | Description
prompt | Required. String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return-linefeed character combination (Chr(13) & Chr(10)) between each line.
title | Optional. String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.
default | Optional. String expression displayed in the text box as the default response if no other input is provided. If you omit default, the text box is displayed empty.
xpos | Optional. Numeric expression that specifies, in twips, the horizontal distance of the left edge of the dialog box from the left edge of the screen. If xpos is omitted, the dialog box is horizontally centered.
ypos | Optional. Numeric expression that specifies, in twips, the vertical distance of the upper edge of the dialog box from the top of the screen. If ypos is omitted, the dialog box is vertically positioned approximately one-third of the way down the screen.
helpfile | Optional. String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided.
context | Optional. Numeric expression that is the Help context number assigned to the appropriate Help topic by the Help author. If context is provided, helpfile must also be provided.

Remarks

When both helpfile and context are provided, the user can press F1 (Windows) or HELP (Macintosh) to view the Help topic corresponding to the context. Some host applications, for example, Microsoft Excel, also automatically add a Help button to the dialog box. If the user clicks OK or presses ENTER , the InputBox function returns whatever is in the text box. If the user clicks Cancel, the function returns a zero-length string ("").

Note Note

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

InputBox Function Example

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

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

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

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


InStr Function

 Copy code hover
[image]

InStr Function
Send feedback

Returns a Variant (Long) specifying the position of the first occurrence of one string within another.

Syntax

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

The InStr function syntax has these arguments:

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

Settings

The compare argument settings are:

Constant | Value | Description
vbUseCompareOption | -1 | Performs a comparison using the setting of the Option Compare statement.
vbBinaryCompare | 0 | Performs a binary comparison.
vbTextCompare | 1 | Performs a textual comparison.
vbDatabaseCompare | 2 | Microsoft Access only. Performs a comparison based on information in your database.

Return Values

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

Remarks

The InStrB function is used with byte data contained in a string. Instead of returning the character position of the first occurrence of one string within another, InStrB returns the byte position.

Example

This example uses the InStr function to return the position of the first occurrence of one string within another.


InStrRev Function

 Copy code hover
[image]

InStrRev Function
Send feedback

Description

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

Syntax

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

The InstrRev function syntax has these named arguments:

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

Settings

The compare argument can have the following values:

Constant | Value | Description
vbUseCompareOption | -1 | Performs a comparison using the setting of the Option Compare statement.
vbBinaryCompare | 0 | Performs a binary comparison.
vbTextCompare | 1 | Performs a textual comparison.
vbDatabaseCompare | 2 | Microsoft Access only. Performs a comparison based on information in your database.

Return Values

InStrRev returns the following values:

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

Remarks

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


Int, Fix Functions

 Copy code hover
[image]

Int, Fix Functions
Send feedback

Returns the integer portion of a number.

Syntax

Int( number )

Fix( number )

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

Remarks

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

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

Fix( number ) is equivalent to:

Copy code Copy code
Sgn(number) * Int(Abs(number))

Example

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

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

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

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


IPmt Function

 Copy code hover
[image]

IPmt Function
Send feedback

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

Syntax

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

The IPmt function has these named arguments:

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

Remarks

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

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

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

Example

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

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


IRR Function

 Copy code hover
[image]

IRR Function
Send feedback

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

Syntax

IRR(values()[, guess])

The IRR function has these named arguments:

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

Remarks

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

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

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

Example

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

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


IsArray Function

 Copy code hover
[image]

IsArray Function
Send feedback

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

Syntax

IsArray( varname )

The required varname argument is an identifier specifying a variable.

Remarks

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

Example

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

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


IsDate Function

 Copy code hover
[image]

IsDate Function
Send feedback

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

Syntax

IsDate( expression )

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

Remarks

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

Example

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

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

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

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


IsEmpty Function

 Copy code hover
[image]

IsEmpty Function
Send feedback

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

Syntax

IsEmpty( expression )

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

Remarks

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

Example

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

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

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

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


IsError Function

 Copy code hover
[image]

IsError Function
Send feedback

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

Syntax

IsError( expression )

The required expression argument can be any valid expression.

Remarks

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

Example

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

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


IsMissing Function

 Copy code hover
[image]

IsMissing Function
Send feedback

Returns a Boolean value indicating whether an optional Variant argument has been passed to a procedure.

Syntax

IsMissing( argname )

The required argname argument contains the name of an optional Variant procedure argument.

Remarks

Use the IsMissing function to detect whether or not optional Variant arguments have been provided in calling a procedure. IsMissing returns True if no value has been passed for the specified argument; otherwise, it returns False. If IsMissing returns True for an argument, use of the missing argument in other code may cause a user-defined error. If IsMissing is used on a ParamArray argument, it always returns False. To detect an empty ParamArray, test to see if the array's upper bound is less than its lower bound.

Note Note

IsMissing does not work on simple data types (such as Integer or Double) because, unlike Variants, they don't have a provision for a "missing" flag bit. Because of this, the syntax for typed optional arguments allows you to specify a default value. If the argument is omitted when the procedure is called, then the argument will have this default value, as in the example below:
Copy code Copy code
Sub MySub(Optional MyVar As String = "specialvalue")
    If MyVar = "specialvalue" Then
        ' MyVar was omitted.
    Else
    ...
End Sub

In many cases you can omit the If MyVar test entirely by making the default value equal to the value you want MyVar to contain if the user omits it from the function call. This makes your code more concise and efficient.

Example

This example uses the IsMissing function to check if an optional argument has been passed to a user-defined procedure. Note that Optional arguments can now have default values and types other than Variant.

VBA Copy code Copy code
Dim ReturnValue
' The following statements call the user-defined function procedure.
ReturnValue = ReturnTwice()    ' Returns Null.
ReturnValue = ReturnTwice(2)    ' Returns 4.

' Function procedure definition.
Function ReturnTwice(Optional A)
    If IsMissing(A) Then
        ' If argument is missing, return a Null.
        ReturnTwice = Null
    Else
        ' If argument is present, return twice the value.
        ReturnTwice = A * 2
    End If
End Function


IsNull Function

 Copy code hover
[image]

IsNull Function
Send feedback

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

Syntax

IsNull( expression )

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

Remarks

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

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

Important note Important

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

Example

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

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

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

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


IsNumeric Function

 Copy code hover
[image]

IsNumeric Function
Send feedback

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

Syntax

IsNumeric( expression )

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

Remarks

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

IsNumeric returns False if expression is a date expression.

Example

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

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

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

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


IsObject Function

 Copy code hover
[image]

IsObject Function
Send feedback

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

Syntax

IsObject( identifier )

The required identifier argument is a variable name.

Remarks

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

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

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

Example

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

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


Join Function

 Copy code hover
[image]

Join Function
Send feedback

Description

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

Syntax

Join(sourcearray[, delimiter])

The Join function syntax has these named arguments:

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


LBound Function

 Copy code hover
[image]

LBound Function
Send feedback

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

Syntax

LBound( arrayname[, dimension])

The LBound function syntax has these parts:

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

Remarks

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

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

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. The base of an array created with the Array function is zero; it is unaffected by Option Base.

Arrays for which dimensions are set using the To clause in a Dim, Private, Public, ReDim, or Static statement can have any integer value as a lower bound.

Example

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

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


LCase Function

 Copy code hover
[image]

LCase Function
Send feedback

Returns a String that has been converted to lowercase.

Syntax

LCase(string)

The required string argument is any valid string expression. If string contains Null, Null is returned.

Remarks

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

Example

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

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


Left Function

 Copy code hover
[image]

Left Function
Send feedback

Returns a Variant (String) containing a specified number of characters from the left side of a string.

Syntax

Left(string, length)

The Left function syntax has these named arguments:

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

Remarks

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

Note Note

Use the LeftB function with byte data contained in a string. Instead of specifying the number of characters to return, length specifies the number of bytes.

Example

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

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


Len Function

 Copy code hover
[image]

Len Function
Send feedback

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

Syntax

Len(string | varname)

The Len function syntax has these parts:

Part | Description
string | Any valid string expression. If string contains Null, Null is returned.
Varname | Any valid variable name. If varname contains Null, Null is returned. If varname is a Variant, Len treats it the same as a String and always returns the number of characters it contains.

Remarks

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

Note Note

Use the LenB function with byte data contained in a string, as in double-byte character set (DBCS) languages. Instead of returning the number of characters in a string, LenB returns the number of bytes used to represent that string. With user-defined types, LenB returns the in-memory size, including any padding between elements. For sample code that uses LenB, see the second example in the example topic.
Note Note

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

Example

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

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

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

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

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

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


Loc Function

 Copy code hover
[image]

Loc Function
Send feedback

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

Syntax

Loc( filenumber )

The required filenumber argument is any valid Integer file number.

Remarks

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

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

Example

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

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


LOF Function

 Copy code hover
[image]

LOF Function
Send feedback

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

Syntax

LOF( filenumber )

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

Note Note

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

Example

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

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


Log Function

 Copy code hover
[image]

Log Function
Send feedback

Returns a Double specifying the natural logarithm of a number.

Syntax

Log( number )

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

Remarks

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

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

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

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

Copy code Copy code
Static Function Log10(X)
    Log10 = Log(X) / Log(10#)
End Function

Example

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

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


LTrim, RTrim, and Trim Functions

 Copy code hover
[image]

LTrim, RTrim, and Trim Functions
Send feedback

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

Syntax

LTrim(string)

RTrim(string)

Trim(string)

The required string argument is any valid string expression. If string contains Null, Null is returned.

Example

This example uses the LTrim function to strip leading spaces and the RTrim function to strip trailing spaces from a string variable. It uses the Trim function to strip both types of spaces.

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


MacID Function

 Copy code hover
[image]

MacID Function
Send feedback

Used on the Macintosh to convert a 4-character constant to a value that may be used by Dir, Kill, Shell, and AppActivate.

Syntax

MacID(constant)

The required constant argument consists of 4 characters used to specify a resource type, file type, application signature, or Apple Event, for example, TEXT, OBIN, "XLS5" for Excel files ("XLS8" for Excel 97), Microsoft Word uses "W6BN" ("W8BN" for Word 97), and so on.

Remarks

MacID is used with Dir and Kill to specify a Macintosh file type. Since the Macintosh does not support * and ? as wildcards, you can use a four-character constant instead to identify groups of files. For example, the following statement returns TEXT type files from the current folder:

Copy code Copy code
Dir("SomePath", MacID("TEXT"))

MacID is used with Shell and AppActivate to specify an application using the application's unique signature.


MacScript Function

 Copy code hover
[image]

MacScript Function
Send feedback

Executes an AppleScript script and returns a value returned by the script, if any.

Syntax

MacScript script

The script argument is a String expression. The String expression either can be a series of AppleScript commands or can specify the name of an AppleScript script or a script file.

Remarks

Multiline scripts can be created by embedding carriage-return characters (Chr(13)).

Example

This example uses the MacScript function to open the Choose File dialog box (the Macintosh standard-file dialog). The full path of the file chosen by the user is returned. If appropriate, the path specification is preceded by the type of the file.

Copy code Copy code
ThePath$ = Macscript("ChooseFile")


Math Functions

 Copy code hover
[image]

Math Functions
Send feedback

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


Mid Function

 Copy code hover
[image]

Mid Function
Send feedback

Returns a Variant (String) containing a specified number of characters from a string.

Syntax

Mid(string, start[, length])

The Mid function syntax has these named arguments:

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

Remarks

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

Note Note

Use the MidB function with byte data contained in a string, as in double-byte character set languages. Instead of specifying the number of characters, the arguments specify numbers of bytes. For sample code that uses MidB, see the second example in the example topic.

Example

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

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

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

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

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


Minute Function

 Copy code hover
[image]

Minute Function
Send feedback

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

Syntax

Minute( time )

The required time argument is any Variant, numeric expression, string expression, or any combination, that can represent a time. If time contains Null, Null is returned.

Example

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

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


MIRR Function

 Copy code hover
[image]

MIRR Function
Send feedback

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

Syntax

MIRR(values(), finance_rate , reinvest_rate)

The MIRR function has these named arguments:

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

Remarks

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

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

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

Example

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

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


Month Function

 Copy code hover
[image]

Month Function
Send feedback

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

Syntax

Month( date )

The required date argument is any Variant, numeric expression, string expression, or any combination, that can represent a date. If date contains Null, Null is returned.

Note Note

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

Example

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

Copy code Copy code
Dim MyDate, MyMonth
MyDate = #February 12, 1969#    ' Assign a date.
MyMonth = Month(MyDate)    ' MyMonth contains 2.


MonthName Function

 Copy code hover
[image]

MonthName Function
Send feedback

Description

Returns a string indicating the specified month.

Syntax

MonthName( month[, abbreviate])

The MonthName function syntax has these parts:

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


MsgBox Function

 Copy code hover
[image]

MsgBox Function
Send feedback

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

Syntax

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

The MsgBox function syntax has these named arguments:

Part | Description
prompt | Required. String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return - linefeed character combination (Chr(13) & Chr(10)) between each line.
buttons | Optional. Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If omitted, the default value for buttons is 0.
title | Optional. String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.
helpfile | Optional. String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided.
context | Optional. Numeric expression that is the Help context number assigned to the appropriate Help topic by the Help author. If context is provided, helpfile must also be provided.

Settings

The buttons argument settings are:

Constant | Value | Description
vbOKOnly | 0 | Display OK button only.
vbOKCancel | 1 | Display OK and Cancel buttons.
vbAbortRetryIgnore | 2 | Display Abort, Retry, and Ignore buttons.
vbYesNoCancel | 3 | Display Yes, No, and Cancel buttons.
vbYesNo | 4 | Display Yes and No buttons.
vbRetryCancel | 5 | Display Retry and Cancel buttons.
vbCritical | 16 | Display Critical Message icon.
vbQuestion | 32 | Display Warning Query icon.
vbExclamation | 48 | Display Warning Message icon.
vbInformation | 64 | Display Information Message icon.
vbDefaultButton1 | 0 | First button is default.
vbDefaultButton2 | 256 | Second button is default.
vbDefaultButton3 | 512 | Third button is default.
vbDefaultButton4 | 768 | Fourth button is default.
vbApplicationModal | 0 | Application modal; the user must respond to the message box before continuing work in the current application.
vbSystemModal | 4096 | System modal; all applications are suspended until the user responds to the message box.
vbMsgBoxHelpButton | 16384 | Adds Help button to the message box.
VbMsgBoxSetForeground | 65536 | Specifies the message box window as the foreground window.
vbMsgBoxRight | 524288 | Text is right aligned.
vbMsgBoxRtlReading | 1048576 | Specifies text should appear as right-to-left reading on Hebrew and Arabic systems.

The first group of values (0-5) describes the number and type of buttons displayed in the dialog box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512) determines which button is the default; and the fourth group (0, 4096) determines the modality of the message box. When adding numbers to create a final value for the buttons argument, use only one number from each group.

Note Note

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

Return Values

Constant | Value | Description
vbOK | 1 | OK
vbCancel | 2 | Cancel
vbAbort | 3 | Abort
vbRetry | 4 | Retry
vbIgnore | 5 | Ignore
vbYes | 6 | Yes
vbNo | 7 | No

Remarks

When both helpfile and context are provided, the user can press F1 (Windows) or HELP (Macintosh) to view the Help topic corresponding to the context. Some host applications, for example, Microsoft Excel, also automatically add a Help button to the dialog box.

If the dialog box displays a Cancel button, pressing the ESC key has the same effect as clicking Cancel. If the dialog box contains a Help button, context-sensitive Help is provided for the dialog box. However, no value is returned until one of the other buttons is clicked.

Note Note

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

Example

This example uses the MsgBox function to display a critical-error message in a dialog box with Yes and No buttons. The No button is specified as the default response. The value returned by the MsgBox function depends on the button chosen by the user. This example assumes that DEMO.HLP is a Help file that contains a topic with a Help context number equal to is a Help file that contains a topic with a Help context number equal to 1000 .

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


Now Function

 Copy code hover
[image]

Now Function
Send feedback

Returns a Variant (Date) specifying the current date and time according your computer's system date and time.

Syntax

Now

Example

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

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


NPer Function

 Copy code hover
[image]

NPer Function
Send feedback

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

Syntax

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

The NPer function has these named arguments:

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

Remarks

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

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

Example

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

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


NPV Function

 Copy code hover
[image]

NPV Function
Send feedback

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

Syntax

NPV(rate, values())

The NPV function has these named arguments:

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

Remarks

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

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

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

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

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

Example

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

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


Oct Function

 Copy code hover
[image]

Oct Function
Send feedback

Returns a Variant (String) representing the octal value of a number.

Syntax

Oct(number)

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

Remarks

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

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

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

Example

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

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


Partition Function

 Copy code hover
[image]

Partition Function
Send feedback

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

Syntax

Partition(number, start, stop, interval)

The Partition function syntax has these named arguments:

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

Remarks

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

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

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

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

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

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

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

Example

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

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


Pmt Function

 Copy code hover
[image]

Pmt Function
Send feedback

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

Syntax

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

The Pmt function has these named arguments:

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

Remarks

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

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

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

Example

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

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


PPmt Function

 Copy code hover
[image]

PPmt Function
Send feedback

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

Syntax

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

The PPmt function has these named arguments:

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

Remarks

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

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

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

Example

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

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


PV Function

 Copy code hover
[image]

PV Function
Send feedback

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

Syntax

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

The PV function has these named arguments:

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

Remarks

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

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

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

Example

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

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


QBColor Function

 Copy code hover
[image]

QBColor Function
Send feedback

Returns a Long representing the RGB color code corresponding to the specified color number.

Syntax

QBColor( color )

The required color argument is a whole number in the range 0-15.

Settings

The color argument has these settings:

Number | Color | Number | Color
0 | Black | 8 | Gray
1 | Blue | 9 | Light Blue
2 | Green | 10 | Light Green
3 | Cyan | 11 | Light Cyan
4 | Red | 12 | Light Red
5 | Magenta | 13 | Light Magenta
6 | Yellow | 14 | Light Yellow
7 | White | 15 | Bright White

Remarks

The color argument represents color values used by earlier versions of Basic (such as Microsoft Visual Basic for MS-DOS and the 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 for Applications.

Example

This example uses the QBColor function to change the BackColor property of the form passed in as MyForm to the color indicated by ColorCode. QBColor accepts integer values between 0 and 15.

VBA Copy code Copy code
Sub ChangeBackColor (ColorCode As Integer, MyForm As Form)
    MyForm.BackColor = QBColor(ColorCode)
End Sub


Rate Function

 Copy code hover
[image]

Rate Function
Send feedback

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

Syntax

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

The Rate function has these named arguments:

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

Remarks

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

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

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

Example

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

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


Replace Function

 Copy code hover
[image]

Replace Function
Send feedback

Description

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

Syntax

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

The Replace function syntax has these named arguments:

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

Settings

The compare argument can have the following values:

Constant | Value | Description
vbUseCompareOption | -1 | Performs a comparison using the setting of the Option Compare statement.
vbBinaryCompare | 0 | Performs a binary comparison.
vbTextCompare | 1 | Performs a textual comparison.
vbDatabaseCompare | 2 | Microsoft Access only. Performs a comparison based on information in your database.

Return Values

Replace returns the following values:

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

Remarks

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


RGB Function

 Copy code hover
[image]

RGB Function
Send feedback

Returns a Long whole number representing an RGB color value.

Syntax

RGB(red, green, blue)

The RGB function syntax has these named arguments:

Part | Description
red | Required; Variant (Integer). Number in the range 0-255, inclusive, that represents the red component of the color.
green | Required; Variant (Integer). Number in the range 0-255, inclusive, that represents the green component of the color.
blue | Required; Variant (Integer). Number in the range 0-255, inclusive, that represents the blue component of the color.

Remarks

Application methods and properties that accept a color specification expect that specification to be a number representing an RGB color value. An RGB color value specifies the relative intensity of red, green, and blue to cause a specific color to be displayed.

The value for any argument to RGB that exceeds 255 is assumed to be 255.

The following table lists some standard colors and the red, green, and blue values they include:

Color | Red Value | Green Value | Blue Value
Black | 0 | 0 | 0
Blue | 0 | 0 | 255
Green | 0 | 255 | 0
Cyan | 0 | 255 | 255
Red | 255 | 0 | 0
Magenta | 255 | 0 | 255
Yellow | 255 | 255 | 0
White | 255 | 255 | 255

The RGB color values returned by this function are incompatible with those used by the Macintosh operating system. They may be used within the context of Microsoft applications for the Macintosh, but should not be used when communicating color changes directly to the Macintosh operating system.

Example

This example shows how the RGB function is used to return a whole number representing an RGB color value. It is used for those application methods and properties that accept a color specification. The object MyObject and its property are used for illustration purposes only. If MyObject does not exist, or if it does not have a Color property, an error occurs.

VBA Copy code Copy code
Dim RED, I, RGBValue, MyObject
Red = RGB(255, 0, 0)    ' Return the value for Red.
I = 75    ' Initialize offset.
RGBValue = RGB(I, 64 + I, 128 + I)     ' Same as RGB(75, 139, 203).
MyObject.Color = RGB(255, 0, 0)    ' Set the Color property of
    ' MyObject to Red.


Right Function

 Copy code hover
[image]

Right Function
Send feedback

Returns a Variant (String) containing a specified number of characters from the right side of a string.

Syntax

Right(string, length)

The Right function syntax has these named arguments:

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

Remarks

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

Note Note

Use the RightB function with byte data contained in a string. Instead of specifying the number of characters to return, length specifies the number of bytes.

Example

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

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


Rnd Function

 Copy code hover
[image]

Rnd Function
Send feedback

Returns a Single containing a random number.

Syntax

Rnd[(number)]

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

Return Values

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

Remarks

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

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

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

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

To produce random integers in a given range, use this formula:

Copy code Copy code
Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.

Note Note

To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.

Example

This example uses the Rnd function to generate a random integer value from 1 to 6.

Copy code Copy code
Dim MyValue
MyValue = Int((6 * Rnd) + 1)    ' Generate random value between 1 and 6.


Round Function

 Copy code hover
[image]

Round Function
Send feedback

Description

Returns a number rounded to a specified number of decimal places.

Syntax

Round( expression [,numdecimalplaces])

The Round function syntax has these parts:

Part | Description
expression | Required. Numeric expression being rounded.
numdecimalplaces | Optional. Number indicating how many places to the right of the decimal are included in the rounding. If omitted, integers are returned by the Round function.


Second Function

 Copy code hover
[image]

Second Function
Send feedback

Returns a Variant (Integer) specifying a whole number between 0 and 59, inclusive, representing the second of the minute.

Syntax

Second( time )

The required time argument is any Variant, numeric expression, string expression, or any combination, that can represent a time. If time contains Null, Null is returned.

Example

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

Copy code Copy code
Dim MyTime, MySecond
MyTime = #4:35:17 PM#    ' Assign a time.
MySecond = Second(MyTime)    ' MySecond contains 17.


Seek Function

 Copy code hover
[image]

Seek Function
Send feedback

Returns a Long specifying the current read/write position within a file opened using the Open statement.

Syntax

Seek( filenumber )

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

Remarks

Seek returns a value between 1 and 2,147,483,647 (equivalent to 2^31 - 1), inclusive.

The following describes the return values for each file access mode.

Mode | Return Value
Random | Number of the next record read or written
Binary, Output, Append, Input | Byte position at which the next operation takes place. The first byte in a file is at position 1, the second byte is at position 2, and so on.

Example

This example uses the Seek function to return the current file position. The example assumes TESTFILE is a file containing records of the user-defined type is a file containing records of the user-defined type Record .

VBA Copy code Copy code
Type Record    ' Define user-defined type.
    ID As Integer
    Name As String * 20
End Type

For files opened in Random mode, Seek returns number of next record.

Copy code Copy code
Dim MyRecord As Record    ' Declare variable.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
Do While Not EOF(1)    ' Loop until end of file.
    Get #1, , MyRecord    ' Read next record.
    Debug.Print Seek(1)    ' Print record number to the
            ' Immediate window.
Loop
Close #1    ' Close file.

For files opened in modes other than Random mode, Seek returns the byte position at which the next operation takes place. Assume TESTFILE is a file containing a few lines of text.

VBA Copy code Copy code
Dim MyChar
Open "TESTFILE" For Input As #1    ' Open file for reading.
Do While Not EOF(1)    ' Loop until end of file.
    MyChar = Input(1, #1)    ' Read next character of data.
    Debug.Print Seek(1)    ' Print byte position to the
            ' Immediate window.
Loop
Close #1    ' Close file.


Sgn Function

 Copy code hover
[image]

Sgn Function
Send feedback

Returns a Variant (Integer) indicating the sign of a number.

Syntax

Sgn( number )

The required number argument can be any valid numeric expression.

Return Values

If number is | Sgn returns
Greater than zero | 1
Equal to zero | 0
Less than zero | -1

Remarks

The sign of the number argument determines the return value of the Sgn function.

Example

This example uses the Sgn function to determine the sign of a number.

VBA Copy code Copy code
Dim MyVar1, MyVar2, MyVar3, MySign
MyVar1 = 12: MyVar2 = -2.4: MyVar3 = 0
MySign = Sgn(MyVar1)    ' Returns 1.
MySign = Sgn(MyVar2)    ' Returns -1.
MySign = Sgn(MyVar3)    ' Returns 0.


Shell Function

 Copy code hover
[image]

Shell Function
Send feedback

Runs an executable program and returns a Variant (Double) representing the program's task ID if successful, otherwise it returns zero.

Syntax

Shell(pathname[,windowstyle])

The Shell function syntax has these named arguments:

Part | Description
pathname | Required; Variant (String). Name of the program to execute and any required arguments or command-line switches; may include directory or folder and drive. On the Macintosh, you can use the MacID function to specify an application's signature instead of its name. The following example uses the signature for Microsoft Word: Shell MacID("MSWD")
windowstyle | Optional. Variant (Integer) corresponding to the style of the window in which the program is to be run. If windowstyle is omitted, the program is started minimized with focus. On the Macintosh (System 7.0 or later), windowstyle only determines whether or not the application gets the focus when it is run.

The windowstyle named argument has these values:

Constant | Value | Description
vbHide | 0 | Window is hidden and focus is passed to the hidden window. The vbHide constant is not applicable on Macintosh platforms.
vbNormalFocus | 1 | Window has focus and is restored to its original size and position.
vbMinimizedFocus | 2 | Window is displayed as an icon with focus.
vbMaximizedFocus | 3 | Window is maximized with focus.
vbNormalNoFocus | 4 | Window is restored to its most recent size and position. The currently active window remains active.
vbMinimizedNoFocus | 6 | Window is displayed as an icon. The currently active window remains active.

Remarks

If the Shell function successfully executes the named file, it returns the task 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.

On the Macintosh, vbNormalFocus, vbMinimizedFocus, and vbMaximizedFocus all place the application in the foreground; vbHide, vbNoFocus, vbMinimizeFocus all place the application in the background.

Note Note

By default, the Shell function runs other programs asynchronously. This means that a program started with Shell might not finish executing before the statements following the Shell function are executed.

Example

This example uses the Shell function to run an application specified by the user. On the MacIntosh, the default drive name is "HD" and portions of the pathname are separated by colons instead of backslashes. Similarly, you would specify Macintosh folders instead of \Windows.

Copy code Copy code
' Specifying 1 as the second argument opens the application in
' normal size and gives it the focus.
Dim RetVal
RetVal = Shell("C:\WINDOWS\CALC.EXE", 1)    ' Run Calculator.


Sin Function

 Copy code hover
[image]

Sin Function
Send feedback

Returns a Double specifying the sine of an angle.

Syntax

Sin( number )

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

Remarks

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

The result lies in the range -1 to 1.

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

Example

This example uses the Sin function to return the sine of an angle.

Copy code Copy code
Dim MyAngle, MyCosecant
MyAngle = 1.3    ' Define angle in radians.
MyCosecant = 1 / Sin(MyAngle)    ' Calculate cosecant.


SLN Function

 Copy code hover
[image]

SLN Function
Send feedback

Returns a Double specifying the straight-line depreciation of an asset for a single period.

Syntax

SLN(cost, salvage, life)

The SLN function has these named arguments:

Part | Description
cost | Required. Double specifying initial cost of the asset.
salvage | Required. Double specifying value of the asset at the end of its useful life.
life | Required. Double specifying length of the useful life of the asset.

Remarks

The depreciation period must be expressed in the same unit as the life argument. All arguments must be positive numbers.

Example

This example uses the SLN function to return the straight-line depreciation of an asset for a single period given the asset's initial cost (InitCost), the salvage value at the end of the asset's useful life (SalvageVal), and the total life of the asset in years (LifeTime).

VBA Copy code Copy code
Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, PDepr
Const YEARMONTHS = 12    ' Number of months in a year.
Fmt = "###,##0.00"    ' Define money format.
InitCost = InputBox("What's the initial cost of the asset?")
SalvageVal = InputBox("What's the asset's value at the end of its useful life?")
MonthLife = InputBox("What's the asset's useful life in months?")
Do While MonthLife < YEARMONTHS    ' Ensure period is >= 1 year.
    MsgBox "Asset life must be a year or more."
    MonthLife = InputBox("What's the asset's useful life in months?")
Loop
LifeTime = MonthLife / YEARMONTHS    ' Convert months to years.
If LifeTime <> Int(MonthLife / YEARMONTHS) Then
    LifeTime = Int(LifeTime + 1)    ' Round up to nearest year.
End If
PDepr = SLN(InitCost, SalvageVal, LifeTime)
MsgBox "The depreciation is " & Format(PDepr, Fmt) & " per year."


Space Function

 Copy code hover
[image]

Space Function
Send feedback

Returns a Variant (String) consisting of the specified number of spaces.

Syntax

Space(number)

The required number argument is the number of spaces you want in the string.

Remarks

The Space function is useful for formatting output and clearing data in fixed-length strings.

Example

This example uses the Space function to return a string consisting of a specified number of spaces.

Copy code Copy code
Dim MyString
' Returns a string with 10 spaces.
MyString = Space(10)

' Insert 10 spaces between two strings.
MyString = "Hello" & Space(10) & "World"


Spc Function

 Copy code hover
[image]

Spc Function
Send feedback

Used with the Print # statement or the Print method to position output.

Syntax

Spc( n )

The required n argument is the number of spaces to insert before displaying or printing the next expression in a list.

Remarks

If n is less than the output line width, the next print position immediately follows the number of spaces printed. If n is greater than the output line width, Spc calculates the next print position using the formula:

currentprintposition + (n Mod width)

For example, if the current print position is 24, the output line width is 80, and you specify Spc(90), the next print will start at position 34 (current print position + the remainder of 90/80). If the difference between the current print position and the output line width is less than n (or n Mod width), the Spc function skips to the beginning of the next line and generates spaces equal to n - (width - currentprintposition).

Note Note

Make sure your tabular columns are wide enough to accommodate wide letters.

When you use the Print method with a proportionally spaced font, the width of space characters printed using the Spc function is always an average of the width of all characters in the point size for the chosen font. However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter i occupies less than one fixed-width column.

Example

This example uses the Spc function to position output in a file and in the Immediate window.

Copy code Copy code
' The Spc function can be used with the Print # statement.
Open "TESTFILE" For Output As #1    ' Open file for output.
Print #1, "10 spaces between here"; Spc(10); "and here."
Close #1    ' Close file.

The following statement causes the text to be printed in the Immediate window (using the Print method), preceded by 30 spaces.

Copy code Copy code
Debug.Print Spc(30); "Thirty spaces later..."


Split Function

 Copy code hover
[image]

Split Function
Send feedback

Description

Returns a zero-based, one-dimensional array containing a specified number of substrings.

Syntax

Split(expression[, delimiter[, limit[, compare]]])

The Split function syntax has these named arguments:

Part | Description
expression | Required. String expression containing substrings and delimiters. If expression is a zero-length string(""), Split returns an empty array, that is, an array with no elements and no data.
delimiter | Optional. String character used to identify substring limits. If omitted, the space character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.
limit | Optional. Number of substrings to be returned; -1 indicates that all substrings are returned.
compare | Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.

Settings

The compare argument can have the following values:

Constant | Value | Description
vbUseCompareOption | -1 | Performs a comparison using the setting of the Option Compare statement.
vbBinaryCompare | 0 | Performs a binary comparison.
vbTextCompare | 1 | Performs a textual comparison.
vbDatabaseCompare | 2 | Microsoft Access only. Performs a comparison based on information in your database.


Sqr Function

 Copy code hover
[image]

Sqr Function
Send feedback

Returns a Double specifying the square root of a number.

Syntax

Sqr( number )

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

Example

This example uses the Sqr function to calculate the square root of a number.

Copy code Copy code
Dim MySqr
MySqr = Sqr(4)    ' Returns 2.
MySqr = Sqr(23)    ' Returns 4.79583152331272.
MySqr = Sqr(0)    ' Returns 0.
MySqr = Sqr(-4)    ' Generates a run-time error.


Str Function

 Copy code hover
[image]

Str Function
Send feedback

Returns a Variant (String) representation of a number.

Syntax

Str(number)

The required number argument is a Long containing any valid numeric expression.

Remarks

When numbers are converted to strings, a leading space is always reserved for the sign of number. If number is positive, the returned string contains a leading space and the plus sign is implied.

Use the Format function to convert numeric values you want formatted as dates, times, or currency or in other user-defined formats. Unlike Str, the Format function doesn't include a leading space for the sign of number.

Note Note

The Str function recognizes only the period (.) as a valid decimal separator. When different decimal separators may be used (for example, in international applications), use CStr to convert a number to a string.

Example

This example uses the Str function to return a string representation of a number. When a number is converted to a string, a leading space is always reserved for its sign.

Copy code Copy code
Dim MyString
MyString = Str(459)    ' Returns " 459".
MyString = Str(-459.65)    ' Returns "-459.65".
MyString = Str(459.001)    ' Returns " 459.001".


StrComp Function

 Copy code hover
[image]

StrComp Function
Send feedback

Returns a Variant (Integer) indicating the result of a string comparison.

Syntax

StrComp(string1, string2[, compare])

The StrComp function syntax has these named arguments:

Part | Description
string1 | Required. Any valid string expression.
string2 | Required. Any valid string expression.
compare | Optional. Specifies the type of string comparison. If the compare argument is Null, an error occurs. If compare is omitted, the Option Compare setting determines the type of comparison.

Settings

The compare argument settings are:

Constant | Value | Description
vbUseCompareOption | -1 | Performs a comparison using the setting of the Option Compare statement.
vbBinaryCompare | 0 | Performs a binary comparison.
vbTextCompare | 1 | Performs a textual comparison.
vbDatabaseCompare | 2 | Microsoft Access only. Performs a comparison based on information in your database.

Return Values

The StrComp function has the following return values:

If | StrComp returns
string1 is less than string2 | -1
string1 is equal to string2 | 0
string1 is greater than string2 | 1
string1 or string2 is Null | Null

Example

This example uses the StrComp function to return the results of a string comparison. If the third argument is 1, a textual comparison is performed; if the third argument is 0 or omitted, a binary comparison is performed.

Copy code Copy code
Dim MyStr1, MyStr2, MyComp
MyStr1 = "ABCD": MyStr2 = "abcd"    ' Define variables.
MyComp = StrComp(MyStr1, MyStr2, 1)    ' Returns 0.
MyComp = StrComp(MyStr1, MyStr2, 0)    ' Returns -1.
MyComp = StrComp(MyStr2, MyStr1)    ' Returns 1.


StrConv Function

 Copy code hover
[image]

StrConv Function
Send feedback

Returns a Variant (String) converted as specified.

Syntax

StrConv(string, conversion, LCID)

The StrConv function syntax has these named arguments:

Part | Description
string | Required. String expression to be converted.
conversion | Required. Integer. The sum of values specifying the type of conversion to perform.
LCID | Optional. The LocaleID, if different than the system LocaleID. (The system LocaleID is the default.)

Settings

The conversion argument settings are:

Constant | Value | Description
vbUpperCase | 1 | Converts the string to uppercase characters.
vbLowerCase | 2 | Converts the string to lowercase characters.
vbProperCase | 3 | Converts the first letter of every word in string to uppercase.
vbWide* | 4* | Converts narrow (single-byte) characters in string to wide (double-byte) characters.
vbNarrow* | 8* | Converts wide (double-byte) characters in string to narrow (single-byte) characters.
vbKatakana** | 16** | Converts Hiragana characters in string to Katakana characters.
vbHiragana** | 32** | Converts Katakana characters in string to Hiragana characters.
vbUnicode | 64 | Converts the string to Unicode using the default code page of the system. (Not available on the Macintosh.)
vbFromUnicode | 128 | Converts the string from Unicode to the default code page of the system. (Not available on the Macintosh.)

*Applies to East Asia locales.

**Applies to Japan only.

Note Note

These constants are specified by Visual Basic for Applications. As a result, they may be used anywhere in your code in place of the actual values. Most can be combined, for example, vbUpperCase + vbWide, except when they are mutually exclusive, for example, vbUnicode + vbFromUnicode. The constants vbWide, vbNarrow, vbKatakana, and vbHiragana cause run-time errors when used in locales where they do not apply.

The following are valid word separators for proper casing: Null (Chr$(0)), horizontal tab (Chr$(9)), linefeed (Chr$(10)), vertical tab (Chr$(11)), form feed (Chr$(12)), carriage return (Chr$(13)), space (SBCS) (Chr$(32)). The actual value for a space varies by country/region for DBCS.

Remarks

When converting from a Byte array in ANSI format to a string, use the StrConv function. When converting from such an array in Unicode format, use an assignment statement.

Example

This example uses the StrConv function to convert a Unicode string to an ANSI string.

Copy code Copy code
Dim i As Long
Dim x() As Byte
x = StrConv("ABCDEFG", vbFromUnicode)    ' Convert string.
For i = 0 To UBound(x)
    Debug.Print x(i)
Next


String Function

 Copy code hover
[image]

String Function
Send feedback

Returns a Variant (String) containing a repeating character string of the length specified.

Syntax

String(number, character)

The String function syntax has these named arguments:

Part | Description
number | Required; Long. Length of the returned string. If number contains Null, Null is returned.
character | Required; Variant. Character code specifying the character or string expression whose first character is used to build the return string. If character contains Null, Null is returned.

Remarks

If you specify a number for character greater than 255, String converts the number to a valid character code using the formula:

character Mod 256

Example

This example uses the String function to return repeating character strings of the length specified.

Copy code Copy code
Dim MyString
MyString = String(5, "*")    ' Returns "*****".
MyString = String(5, 42)    ' Returns "*****".
MyString = String(10, "ABC")    ' Returns "AAAAAAAAAA".


StrReverse Function

 Copy code hover
[image]

StrReverse Function
Send feedback

Description

Returns a string in which the character order of a specified string is reversed.

Syntax

StrReverse(expression)

The expression argument is the string whose characters are to be reversed. If expression is a zero-length string (""), a zero-length string is returned. If expression is Null, an error occurs.


Switch Function

 Copy code hover
[image]

Switch Function
Send feedback

Evaluates a list of expressions and returns a Variant value or an expression associated with the first expression in the list that is True.

Syntax

Switch( expr-1 , value-1[, expr-2, value-2 … [, expr-n,value-n]])

The Switch function syntax has these parts:

Part | Description
expr | Required. Variant expression you want to evaluate.
value | Required. Value or expression to be returned if the corresponding expression is True.

Remarks

The Switch function argument list consists of pairs of expressions and values. The expressions are evaluated from left to right, and the value associated with the first expression to evaluate to True is returned. If the parts aren't properly paired, a run-time error occurs. For example, if expr-1 is True, Switch returns value-1. If expr-1 is False, but expr-2 is True, Switch returns value-2, and so on.

Switch returns a Null value if:

  • None of the expressions is True.

  • The first True expression has a corresponding value that is Null.

Switch evaluates all of the expressions, even though it returns only one of them. For this reason, you should watch for undesirable side effects. For example, if the evaluation of any expression results in a division by zero error, an error occurs.

Example

This example uses the Switch function to return the name of a language that matches the name of a city.

Copy code Copy code
Function MatchUp (CityName As String)
    Matchup = Switch(CityName = "London", "English", CityName _
                    = "Rome", "Italian", CityName = "Paris", "French")
End Function


SYD Function

 Copy code hover
[image]

SYD Function
Send feedback

Returns a Double specifying the sum-of-years' digits depreciation of an asset for a specified period.

Syntax

SYD(cost, salvage, life, period)

The SYD function has these named arguments:

Part | Description
cost | Required. Double specifying initial cost of the asset.
salvage | Required. Double specifying value of the asset at the end of its useful life.
life | Required. Double specifying length of the useful life of the asset.
period | Required. Double specifying period for which asset depreciation is calculated.

Remarks

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

Example

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

VBA Copy code Copy code
Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, DepYear, PDepr
Const YEARMONTHS = 12    ' Number of months in a year.
Fmt = "###,##0.00"    ' Define money format.
InitCost = InputBox("What's the initial cost of the asset?")
SalvageVal = InputBox("What's the asset's value at the end of its life?")
MonthLife = InputBox("What's the asset's useful life in months?")
Do While MonthLife < YEARMONTHS    ' Ensure period is >= 1 year.
    MsgBox "Asset life must be a year or more."
    MonthLife = InputBox("What's the asset's useful life in months?")
Loop
LifeTime = MonthLife / YEARMONTHS    ' Convert months to years.
If LifeTime <> Int(MonthLife / YEARMONTHS) Then
    LifeTime = Int(LifeTime + 1)    ' Round up to nearest year.
End If
DepYear = CInt(InputBox("For which year do you want depreciation?"))
Do While DepYear < 1 Or DepYear > LifeTime
    MsgBox "You must enter at least 1 but not more than " & LifeTime
    DepYear = CInt(InputBox("For what year do you want depreciation?"))
Loop
PDepr = SYD(InitCost, SalvageVal, LifeTime, DepYear)
MsgBox "The depreciation for year " & DepYear & " is " & Format(PDepr, Fmt) & "."


Tab Function

 Copy code hover
[image]

Tab Function
Send feedback

Used with the Print # statement or the Print method to position output.

Syntax

Tab[(n)]

The optional n argument is the column number moved to before displaying or printing the next expression in a list. If omitted, Tab moves the insertion point to the beginning of the next print zone. This allows Tab to be used instead of a comma in locales where the comma is used as a decimal separator.

Remarks

If the current print position on the current line is greater than n, Tab skips to the nth column on the next output line. If n is less than 1, Tab moves the print position to column 1. If n is greater than the output line width, Tab calculates the next print position using the formula:

n Mod width

For example, if width is 80 and you specify Tab(90), the next print will start at column 10 (the remainder of 90/80). If n is less than the current print position, printing begins on the next line at the calculated print position. If the calculated print position is greater than the current print position, printing begins at the calculated print position on the same line.

The leftmost print position on an output line is always 1. When you use the Print # statement to print to files, the rightmost print position is the current width of the output file, which you can set using the Width # statement.

Note Note

Make sure your tabular columns are wide enough to accommodate wide letters.

When you use the Tab function with the Print method, the print surface is divided into uniform, fixed-width columns. The width of each column is an average of the width of all characters in the point size for the chosen font. However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter i occupies less than one fixed-width column.

Example

This example uses the Tab function to position output in a file and in the Immediate window.

Copy code Copy code
' The Tab function can be used with the Print # statement.
Open "TESTFILE" For Output As #1    ' Open file for output.
' The second word prints at column 20.
Print #1, "Hello"; Tab(20); "World."
' If the argument is omitted, cursor is moved to the next print zone.
Print #1, "Hello"; Tab; "World"
Close #1    ' Close file.

The Tab function can also be used with the Print method. The following statement prints text starting at column 10.

Copy code Copy code
Debug.Print Tab(10); "10 columns from start."


Tan Function

 Copy code hover
[image]

Tan Function
Send feedback

Returns a Double specifying the tangent of an angle.

Syntax

Tan( number )

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

Remarks

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

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

Example

This example uses the Tan function to return the tangent of an angle.

Copy code Copy code
Dim MyAngle, MyCotangent
MyAngle = 1.3    ' Define angle in radians.
MyCotangent = 1 / Tan(MyAngle)    ' Calculate cotangent.


Time Function

 Copy code hover
[image]

Time Function
Send feedback

Returns a Variant (Date) indicating the current system time.

Syntax

Time

Remarks

To set the system time, use the Time statement.

Example

This example uses the Time function to return the current system time.

Copy code Copy code
Dim MyTime
MyTime = Time    ' Return current system time.


Timer Function

 Copy code hover
[image]

Timer Function
Send feedback

Returns a Single representing the number of seconds elapsed since midnight.

Syntax

Timer

Remarks

In Microsoft Windows the Timer function returns fractional portions of a second. On the Macintosh, timer resolution is one second.

Example

This example uses the Timer function to pause the application. The example also uses DoEvents to yield to other processes during the pause.

Copy code Copy code
Dim PauseTime, Start, Finish, TotalTime
If (MsgBox("Press Yes to pause for 5 seconds", 4)) = vbYes Then
    PauseTime = 5    ' Set duration.
    Start = Timer    ' Set start time.
    Do While Timer < Start + PauseTime
        DoEvents    ' Yield to other processes.
    Loop
    Finish = Timer    ' Set end time.
    TotalTime = Finish - Start    ' Calculate total time.
    MsgBox "Paused for " & TotalTime & " seconds"
Else
    End
End If


TimeSerial Function

 Copy code hover
[image]

TimeSerial Function
Send feedback

Returns a Variant (Date) containing the time for a specific hour, minute, and second.

Syntax

TimeSerial(hour, minute, second)

The TimeSerial function syntax has these named arguments:

Part | Description
hour | Required; Variant (Integer). Number between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.
minute | Required; Variant (Integer). Any numeric expression.
second | Required; Variant (Integer). Any numeric expression.

Remarks

To specify a time, such as 11:59:59, the range of numbers for each TimeSerial argument should be in the normal range for the unit; that is, 0-23 for hours and 0-59 for minutes and seconds. However, you can also specify relative times for each argument using any numeric expression that represents some number of hours, minutes, or seconds before or after a certain time. The following example uses expressions instead of absolute time numbers. The TimeSerial function returns a time for 15 minutes before (-15 ) six hours before noon (12 - 6 ), or 5:45:00 A.M.

VBA Copy code Copy code
TimeSerial(12 - 6, -15, 0)

When any argument exceeds the normal range for that argument, it increments to the next larger unit as appropriate. For example, if you specify 75 minutes, it is evaluated as one hour and 15 minutes. If any single argument is outside the range -32,768 to 32,767, an error occurs. If the time specified by the three arguments causes the date to fall outside the acceptable range of dates, an error occurs.

Example

This example uses the TimeSerial function to return a time for the specified hour, minute, and second.

VBA Copy code Copy code
Dim MyTime
MyTime = TimeSerial(16, 35, 17)    ' MyTime contains serial
    ' representation of 4:35:17 PM.


TimeValue Function

 Copy code hover
[image]

TimeValue Function
Send feedback

Returns a Variant (Date) containing the time.

Syntax

TimeValue( time )

The required time argument is normally a string expression representing a time from 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive. However, time can also be any expression that represents a time in that range. If time contains Null, Null is returned.

Remarks

You can enter valid times using a 12-hour or 24-hour clock. For example, "2:24PM" and "14:24" are both valid time arguments.

If the time argument contains date information, TimeValue doesn't return it. However, if time includes invalid date information, an error occurs.

Example

This example uses the TimeValue function to convert a string to a time. You can also use date literals to directly assign a time to a Variant or Date variable, for example, MyTime = #4:35:17 PM#.

Copy code Copy code
Dim MyTime
MyTime = TimeValue("4:35:17 PM")    ' Return a time.


Type Conversion Functions

 Copy code hover
[image]

Type Conversion Functions
Send feedback

Each function coerces an expression to a specific data type.

Syntax

CBool( expression )

CByte( expression )

CCur( expression )

CDate( expression )

CDbl( expression )

CDec( expression )

CInt( expression )

CLng( expression )

CLngLng( expression ) (Valid on 64-bit platforms only.)

CLngPtr( expression )

CSng( expression )

CStr( expression )

CVar( expression )

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

Return Types

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

Function | Return Type | Range for expression argument
CBool | Boolean | Any valid string or numeric expression.
CByte | Byte | 0 to 255.
CCur | Currency | -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
CDate | Date | Any valid date expression.
CDbl | Double | -1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
CDec | Decimal | +/-79,228,162,514,264,337,593,543,950,335 for zero-scaled numbers, that is, numbers with no decimal places. For numbers with 28 decimal places, the range is +/-7.9228162514264337593543950335. The smallest possible non-zero number is 0.0000000000000000000000000001.
CInt | Integer | -32,768 to 32,767; fractions are rounded.
CLng | Long | -2,147,483,648 to 2,147,483,647; fractions are rounded.
CLngLng | LongLong | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807; fractions are rounded. (Valid on 64-bit platforms only.)
CLngPtr | LongPtr | -2,147,483,648 to 2,147,483,647 on 32-bit systems, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 on 64-bit systems; fractions are rounded for 32-bit and 64-bit systems.
CSng | Single | -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
CStr | String | Returns for CStr depend on the expression argument.
CVar | Variant | Same range as Double for numerics. Same range as String for non-numerics.

Remarks

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

Note Note

Conversion functions must be used to explicitly assign LongLong (including LongPtr on 64-bit platforms) to smaller integral types. Implicit conversions of LongLong to smaller integrals are not allowed.

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

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

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

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

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

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

Note Note

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

CBool Function Example

This example uses the CBool function to convert an expression to a Boolean. If the expression evaluates to a nonzero value, CBool returns True; otherwise, it returns False.

Copy code Copy code
Dim A, B, Check
A = 5: B = 5 ' Initialize variables.
Check = CBool(A = B) ' Check contains True.

A = 0 ' Define variable.
Check = CBool(A) ' Check contains False.

CByte Function Example

This example uses the CByte function to convert an expression to a Byte.

Copy code Copy code
Dim MyDouble, MyByte
MyDouble = 125.5678 ' MyDouble is a Double.
MyByte = CByte(MyDouble) ' MyByte contains 126.

CCur Function Example

This example uses the CCur function to convert an expression to a Currency.

Copy code Copy code
Dim MyDouble, MyCurr
MyDouble = 543.214588 ' MyDouble is a Double.
MyCurr = CCur(MyDouble * 2) ' Convert result of MyDouble * 2
 ' (1086.429176) to a
 ' Currency (1086.4292).

CDate Function Example

This example uses the CDate function to convert a string to a Date. In general, hard-coding dates and times as strings (as shown in this example) is not recommended. Use date literals and time literals, such as #2/12/1969# and #4:45:23 PM#, instead.

Copy code Copy code
Dim MyDate, MyShortDate, MyTime, MyShortTime
MyDate = "February 12, 1969" ' Define date.
MyShortDate = CDate(MyDate) ' Convert to Date data type.

MyTime = "4:35:47 PM" ' Define time.
MyShortTime = CDate(MyTime) ' Convert to Date data type.

CDbl Function Example

This example uses the CDbl function to convert an expression to a Double.

Copy code Copy code
Dim MyCurr, MyDouble
MyCurr = CCur(234.456784) ' MyCurr is a Currency.
MyDouble = CDbl(MyCurr * 8.2 * 0.01) ' Convert result to a Double.

CDec Function Example

This example uses the CDec function to convert a numeric value to a Decimal.

Copy code Copy code
Dim MyDecimal, MyCurr
MyCurr = 10000000.0587 ' MyCurr is a Currency.
MyDecimal = CDec(MyCurr) ' MyDecimal is a Decimal.

CInt Function Example

This example uses the CInt function to convert a value to an Integer.

Copy code Copy code
Dim MyDouble, MyInt
MyDouble = 2345.5678 ' MyDouble is a Double.
MyInt = CInt(MyDouble) ' MyInt contains 2346.

CLng Function Example

This example uses the CLng function to convert a value to a Long.

Copy code Copy code
Dim MyVal1, MyVal2, MyLong1, MyLong2
MyVal1 = 25427.45: MyVal2 = 25427.55 ' MyVal1, MyVal2 are Doubles.
MyLong1 = CLng(MyVal1) ' MyLong1 contains 25427.
MyLong2 = CLng(MyVal2) ' MyLong2 contains 25428.

CSng Function Example

This example uses the CSng function to convert a value to a Single.

Copy code Copy code
Dim MyDouble1, MyDouble2, MySingle1, MySingle2
' MyDouble1, MyDouble2 are Doubles.
MyDouble1 = 75.3421115: MyDouble2 = 75.3421555
MySingle1 = CSng(MyDouble1) ' MySingle1 contains 75.34211.
MySingle2 = CSng(MyDouble2) ' MySingle2 contains 75.34216.

CStr Function Example

This example uses the CStr function to convert a numeric value to a String.

Copy code Copy code
Dim MyDouble, MyString
MyDouble = 437.324 ' MyDouble is a Double.
MyString = CStr(MyDouble) ' MyString contains "437.324".

CVar Function Example

This example uses the CVar function to convert an expression to a Variant.

Copy code Copy code
Dim MyInt, MyVar
MyInt = 4534 ' MyInt is an Integer.
MyVar = CVar(MyInt & "000") ' MyVar contains the string
 ' 4534000.


TypeName Function

 Copy code hover
[image]

TypeName Function
Send feedback

Returns a String that provides information about a variable.

Syntax

TypeName( varname )

The required varname argument is a Variant containing any variable except a variable of a user-defined type.

Remarks

The string returned by TypeName can be any one of the following:

String returned | Variable
object type | An object whose type is objecttype
Byte | Byte value
Integer | Integer
Long | Long integer
Single | Single-precision floating-point number
Double | Double-precision floating-point number
Currency | Currency value
Decimal | Decimal value
Date | Date value
String | String
Boolean | Boolean value
Error | An error value
Empty | Uninitialized
Null | No valid data
Object | An object
Unknown | An object whose type is unknown
Nothing | Object variable that doesn't refer to an object

If varname is an array, the returned string can be any one of the possible returned strings (or Variant) with empty parentheses appended. For example, if varname is an array of integers, TypeName returns "Integer()".

Example

This example uses the TypeName function to return information about a variable.

Copy code Copy code
' Declare variables.
Dim NullVar, MyType, StrVar As String, IntVar As Integer, CurVar As Currency
Dim ArrayVar (1 To 5) As Integer
NullVar = Null    ' Assign Null value.
MyType = TypeName(StrVar)    ' Returns "String".
MyType = TypeName(IntVar)    ' Returns "Integer".
MyType = TypeName(CurVar)    ' Returns "Currency".
MyType = TypeName(NullVar)    ' Returns "Null".
MyType = TypeName(ArrayVar)    ' Returns "Integer()".


UBound Function

 Copy code hover
[image]

UBound Function
Send feedback

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

Syntax

UBound( arrayname[, dimension])

The UBound function syntax has these parts:

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

Remarks

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

UBound returns the following values for an array with these dimensions:

Statement | Return Value
UBound(A, 1) | 100
UBound(A, 2) | 3
UBound(A, 3) | 4

Example

This example uses the UBound function to determine the largest available subscript for the indicated dimension of an array.

Copy code Copy code
Dim Upper
Dim MyArray(1 To 10, 5 To 15, 10 To 20)    ' Declare array variables.
Dim AnyArray(10)
Upper = UBound(MyArray, 1)    ' Returns 10.
Upper = UBound(MyArray, 3)    ' Returns 20.
Upper = UBound(AnyArray)    ' Returns 10.


UCase Function

 Copy code hover
[image]

UCase Function
Send feedback

Returns a Variant (String) containing the specified string, converted to uppercase.

Syntax

UCase(string)

The required string argument is any valid string expression. If string contains Null, Null is returned.

Remarks

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

Example

This example uses the UCase function to return an uppercase version of a string.

Copy code Copy code
Dim LowerCase, UpperCase
LowerCase = "Hello World 1234"    ' String to convert.
UpperCase = UCase(LowerCase)    ' Returns "HELLO WORLD 1234".


Val Function

 Copy code hover
[image]

Val Function
Send feedback

Returns the numbers contained in a string as a numeric value of appropriate type.

Syntax

Val( string )

The required string argument is any valid string expression.

Remarks

The Val function stops reading the string at the first character it can't recognize as part of a number. Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized. However, the function recognizes the radix prefixes &O (for octal) and (for octal) and &H (for hexadecimal). Blanks, tabs, and linefeed characters are stripped from the argument.

The following returns the value 1615198:

Copy code Copy code
Val("    1615 198th Street N.E.")

In the code below, Val returns the decimal value -1 for the hexadecimal value shown:

Copy code Copy code
Val("&HFFFF")
Note Note

The Val function recognizes only the period (.) as a valid decimal separator. When different decimal separators are used, as in international applications, use CDbl instead to convert a string to a number.

Example

This example uses the Val function to return the numbers contained in a string.

VBA Copy code Copy code
Dim MyValue
MyValue = Val("2457")    ' Returns 2457.
MyValue = Val(" 2 45 7")    ' Returns 2457.
MyValue = Val("24 and 57")    ' Returns 24.


VarType Function

 Copy code hover
[image]

VarType Function
Send feedback

Returns an Integer indicating the subtype of a variable.

Syntax

VarType( varname )

The required varname argument is a Variant containing any variable except a variable of a user-defined type.

Return Values

Constant | Value | Description
vbEmpty | 0 | Empty (uninitialized)
vbNull | 1 | Null (no valid data)
vbInteger | 2 | Integer
vbLong | 3 | Long integer
vbSingle | 4 | Single-precision floating-point number
vbDouble | 5 | Double-precision floating-point number
vbCurrency | 6 | Currency value
vbDate | 7 | Date value
vbString | 8 | String
vbObject | 9 | Object
vbError | 10 | Error value
vbBoolean | 11 | Boolean value
vbVariant | 12 | Variant (used only with arrays of variants)
vbDataObject | 13 | A data access object
vbDecimal | 14 | Decimal value
vbByte | 17 | Byte value
vbLongLong | 20 | LongLong integer (Valid on 64-bit platforms only.)
vbUserDefinedType | 36 | Variants that contain user-defined types
vbArray | 8192 | Array
Note Note

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

Remarks

The VarType function never returns the value for vbArray by itself. It is always added to some other value to indicate an array of a particular type. The constant vbVariant is only returned in conjunction with vbArray to indicate that the argument to the VarType function is an array of type Variant. For example, the value returned for an array of integers is calculated as vbInteger + vbArray, or 8194. If an object has a default property, VarType (object) returns the type of the object's default property.

Example

This example uses the VarType function to determine the subtype of a variable.

Copy code Copy code
Dim IntVar, StrVar, DateVar, MyCheck
' Initialize variables.
IntVar = 459: StrVar = "Hello World": DateVar = #2/12/69#
MyCheck = VarType(IntVar)    ' Returns 2.
MyCheck = VarType(DateVar)    ' Returns 7.
MyCheck = VarType(StrVar)    ' Returns 8.


Weekday Function

 Copy code hover
[image]

Weekday Function
Send feedback

Returns a Variant (Integer) containing a whole number representing the day of the week.

Syntax

Weekday( date, [firstdayofweek])

The Weekday function syntax has these named arguments:

Part | Description
date | Required. Variant, numeric expression, string expression, or any combination, that can represent a date. If date contains Null, Null is returned.
firstdayofweek | Optional. A constant that specifies the first day of the week. If not specified, vbSunday is assumed.

Settings

The firstdayofweek argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use the NLS API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

Return Values

The Weekday function can return any of these values:

Constant | Value | Description
vbSunday | 1 | Sunday
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

Remarks

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

Example

This example uses the Weekday function to obtain the day of the week from a specified date.

Copy code Copy code
Dim MyDate, MyWeekDay
MyDate = #February 12, 1969#    ' Assign a date.
MyWeekDay = Weekday(MyDate)    ' MyWeekDay contains 4 because
    ' MyDate represents a Wednesday.


WeekdayName Function

 Copy code hover
[image]

WeekdayName Function
Send feedback

Description

Returns a string indicating the specified day of the week.

Syntax

WeekdayName( weekday , abbreviate , firstdayofweek )

The WeekdayName function syntax has these parts:

Part | Description
weekday | Required. The numeric designation for the day of the week. Numeric value of each day depends on setting of the firstdayofweek setting.
abbreviate | Optional. Boolean value that indicates if the weekday name is to be abbreviated. If omitted, the default is False, which means that the weekday name is not abbreviated.
firstdayofweek | Optional. Numeric value indicating the first day of the week. See Settings section for values.

Settings

The firstdayofweek argument can have the following values:

Constant | Value | Description
vbUseSystem | 0 | Use National Language Support (NLS) API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday


Year Function

 Copy code hover
[image]

Year Function
Send feedback

Returns a Variant (Integer) containing a whole number representing the year.

Syntax

Year( date )

The required date argument is any Variant, numeric expression, string expression, or any combination, that can represent a date. If date contains Null, Null is returned.

Note Note

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

Example

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

Copy code Copy code
Dim MyDate, MyYear
MyDate = #February 12, 1969#    ' Assign a date.
MyYear = Year(MyDate)    ' MyYear contains 1969.


Keywords (Visual Basic for Applications)

 Copy code hover
[image]

Keywords (Visual Basic for Applications)
Send feedback

In this section

  • Keywords by Task

  • As <keyword>

  • Binary <keyword>

  • ByRef <keyword>

  • ByVal <keyword>

  • Date <keyword>

  • Else <keyword>

  • Empty <keyword>

  • Error <keyword>

  • False <keyword>

  • For <keyword>

  • Friend <keyword>

  • Get <keyword>

  • Input <keyword>

  • Is <keyword>

  • Len <keyword>

  • Let <keyword>

  • Lock <keyword>

  • Me <keyword>

  • Mid <keyword>

  • New <keyword>

  • Next <keyword>

  • Nothing <keyword>

  • Null <keyword>

  • On <keyword>

  • Option <keyword>

  • Optional <keyword>

  • ParamArray <keyword>

  • Print <keyword>

  • Private <keyword>

  • Property <keyword>

  • PtrSafe <keyword>

  • Public <keyword>

  • Resume <keyword>

  • Seek <keyword>

  • Set <keyword>

  • Static <keyword>

  • Step <keyword>

  • String <keyword>

  • Then <keyword>

  • Time <keyword>

  • To <keyword>

  • True <keyword>

  • WithEvents <keyword>


Keywords by Task

 Copy code hover
[image]

Keywords by Task
Send feedback
Category | Description
Arrays | Creating, defining, and using arrays.
Compiler Directives | Controlling compiler behavior.
Control Flow | Looping and controlling procedure flow.
Conversion | Converting numbers and data types.
Data Types | Data types and variant subtypes.
Dates and Times | Converting and using date and time expressions.
Directories and Files | Controlling the file system and processing files.
Errors | Trapping and returning error values.
Financial | Performing financial calculations.
Input and Output | Receiving input and displaying or printing output.
Math | Performing trigonometric and other mathematical calculations.
Miscellaneous | Starting other applications and processing events.
Operators | Comparing expressions and other operations.
String Manipulation | Manipulating strings and string type data.
Variables and Constants | Declaring and defining variables and constants.


As

 Copy code hover
[image]

As <keyword>
Send feedback

The As keyword is used in these contexts:

Const Statement

Declare Statement

Dim Statement

Function Statement

Name Statement

Open Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

ReDim Statement

Static Statement

Sub Statement

Type Statement


Binary

 Copy code hover
[image]

Binary <keyword>
Send feedback

The Binary keyword is used in these contexts:

Open Statement

Option Compare Statement


ByRef

 Copy code hover
[image]

ByRef <keyword>
Send feedback

The ByRef keyword is used in these contexts:

Call Statement

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


ByVal

 Copy code hover
[image]

ByVal <keyword>
Send feedback

The ByVal keyword is used in these contexts:

Call Statement

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Date

 Copy code hover
[image]

Date <keyword>
Send feedback

The Date keyword is used in these contexts:

Date Data Type

Date Function

Date Statement


Else

 Copy code hover
[image]

Else <keyword>
Send feedback

The Else keyword is used in these contexts:

If...Then...Else Statement

Select Case Statement


Empty

 Copy code hover
[image]

Empty <keyword>
Send feedback

The Empty keyword is used as a Variant subtype. It indicates an uninitialized variable value.


Error

 Copy code hover
[image]

Error <keyword>
Send feedback

The Error keyword is used in these contexts:

Error Function

Error Statement

On Error Statement


False

 Copy code hover
[image]

False <keyword>
Send feedback

The False keyword has a value equal to 0.


For

 Copy code hover
[image]

For <keyword>
Send feedback

The For keyword is used in these contexts:

For...Next Statement

For Each...Next Statement

Open Statement


Friend

 Copy code hover
[image]

Friend <keyword>
Send feedback

Modifies the definition of a procedure in a form module or class module to make the procedure callable from modules that are outside the class, but part of the project within which the class is defined. Friend procedures cannot be used in standard modules.

Syntax

[Private | Friend | Public] [Static] [Sub | Function | Property] procedurename

The required procedurename is the name of the procedure to be made visible throughout the project, but not visible to controllers of the class.

Remarks

Public procedures in a class can be called from anywhere, even by controllers of instances of the class. Declaring a procedure Private prevents controllers of the object from calling the procedure, but also prevents the procedure from being called from within the project in which the class itself is defined. Friend makes the procedure visible throughout the project, but not to a controller of an instance of the object. Friend can appear only in form modules and class modules, and can only modify procedure names, not variables or types. Procedures in a class can access the Friend procedures of all other classes in a project. Friend procedures don't appear in the type library of their class. A Friend procedure can't be late bound.

Friend Example

When placed in a class module, the following code makes the member variable dblBalance accessible to all users of the class within the project. Any user of the class can get the value; only code within the project can assign a value to that variable.

Copy code Copy code
Private dblBalance As Double

Public Property Get Balance() As Double
 Balance = dblBalance
End Property

Friend Property Let Balance(dblNewBalance As Double)
 dblBalance = dblNewBalance
End Property


Get

 Copy code hover
[image]

Get <keyword>
Send feedback

The Get keyword is used in these contexts:

Get Statement

Property Get Statement


Input

 Copy code hover
[image]

Input <keyword>
Send feedback

The Input keyword is used in these contexts:

Input Function

Input # Statement

Line Input # Statement

Open Statement


Is

 Copy code hover
[image]

Is <keyword>
Send feedback

The Is keyword is used in these contexts:

If...Then...Else Statement

Is Operator

Select Case Statement


Len

 Copy code hover
[image]

Len <keyword>
Send feedback

The Len keyword is used in these contexts:

Len Function

Open Statement


Let

 Copy code hover
[image]

Let <keyword>
Send feedback

The Let keyword is used in these contexts:

Let Statement

Property Let Statement


Lock

 Copy code hover
[image]

Lock <keyword>
Send feedback

The Lock keyword is used in these contexts:

Lock, Unlock Statements

Open Statement


Me

 Copy code hover
[image]

Me <keyword>
Send feedback

The Me keyword behaves like an implicitly declared variable. It is automatically available to every procedure in a class module. When a class can have more than one instance, Me provides a way to refer to the specific instance of the class where the code is executing. Using Me is particularly useful for passing information about the currently executing instance of a class to a procedure in another module. For example, suppose you have the following procedure in a module:

Copy code Copy code
Sub ChangeFormColor(FormName As Form)
 FormName.BackColor = RGB(Rnd * 256, Rnd * 256, Rnd * 256)
End Sub

You can call this procedure and pass the current instance of the Form class as an argument using the following statement:

Copy code Copy code
ChangeFormColor Me


Mid

 Copy code hover
[image]

Mid <keyword>
Send feedback

The Mid keyword is used in these contexts:

Mid Function

Mid Statement


New

 Copy code hover
[image]

New <keyword>
Send feedback

The New keyword is used in these contexts:

Dim Statement

Private Statement

Public Statement

Set Statement

Static Statement


Next

 Copy code hover
[image]

Next <keyword>
Send feedback

The Next keyword is used in these contexts:

For...Next Statement

For Each...Next Statement

On Error Statement

Resume Statement


Nothing

 Copy code hover
[image]

Nothing <keyword>
Send feedback

The Nothing keyword is used to disassociate an object variable from an actual object. Use the Set statement to assign Nothing to an object variable. For example:

Copy code Copy code
Set MyObject = Nothing

Several object variables can refer to the same actual object. When Nothing is assigned to an object variable, that variable no longer refers to an actual object. When several object variables refer to the same object, memory and system resources associated with the object to which the variables refer are released only after all of them have been set to Nothing, either explicitly using Set, or implicitly after the last object variable set to Nothing goes out of scope.


Null

 Copy code hover
[image]

Null <keyword>
Send feedback

The Null keyword is used as a Variant subtype. It indicates that a variable contains no valid data.


On

 Copy code hover
[image]

On <keyword>
Send feedback

The On keyword is used in these contexts:

On Error Statement

On...GoSub Statement

On...GoTo Statement


Option

 Copy code hover
[image]

Option <keyword>
Send feedback

The Option keyword is used in these contexts:

Option Base Statement

Option Compare Statement

Option Explicit Statement

Option Private Statement


Optional

 Copy code hover
[image]

Optional <keyword>
Send feedback

The Optional keyword is used in these contexts:

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


ParamArray

 Copy code hover
[image]

ParamArray <keyword>
Send feedback

The ParamArray keyword is used in these contexts:

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Print

 Copy code hover
[image]

Print <keyword>
Send feedback

The Print keyword is used in these contexts:

Print Method

Print # Statement


Private

 Copy code hover
[image]

Private <keyword>
Send feedback

The Private keyword is used in these contexts:

Const Statement

Declare Statement

Enum Statement

Function Statement

Option Private Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement

Type Statement


Property

 Copy code hover
[image]

Property <keyword>
Send feedback

The Property keyword is used in these contexts:

Property Get Statement

Property Let Statement

Property Set Statement


PtrSafe

 Copy code hover
[image]

PtrSafe <keyword>
Send feedback

The PtrSafe keyword is used in this context:

Declare Statement

Note Note

Declare statements with the PtrSafe keyword is the recommended syntax. Declare statements that include PtrSafe work correctly in the VBA7 development environment on both 32-bit and 64-bit platforms only after all data types in the Declare statement (parameters and return values) that need to store 64-bit quantities are updated to use LongLong for 64-bit integrals or LongPtr for pointers and handles. To ensure backwards compatibility with VBA version 6 and earlier use the following construct:
VBA Copy code Copy code
#If Vba7 Then
Declare PtrSafe Sub...
#Else
Declare Sub...
#EndIf

When running in 64-bit versions of Office Declare statements must include the PtrSafe keyword.

The PtrSafe keyword asserts that a Declare statement is safe to run in 64-bit development environments.

Adding the PtrSafe keyword to a Declare statement only signifies the Declare statement explicitly targets 64-bits, all data types within the statement that need to store 64-bits (including return values and parameters) must still be modified to hold 64-bit quantities using either LongLong for 64-bit integrals or LongPtr for pointers and handles.


Public

 Copy code hover
[image]

Public <keyword>
Send feedback

The Public keyword is used in these contexts:

Const Statement

Declare Statement

Enum Statement

Event Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

Sub Statement

Type Statement


Resume

 Copy code hover
[image]

Resume <keyword>
Send feedback

The Resume keyword is used in these contexts:

On Error Statement

Resume Statement


Seek

 Copy code hover
[image]

Seek <keyword>
Send feedback

The Seek keyword is used in these contexts:

Seek Function

Seek Statement


Set

 Copy code hover
[image]

Set <keyword>
Send feedback

The Set keyword is used in these contexts:

Set Statement

Property Set Statement


Static

 Copy code hover
[image]

Static <keyword>
Send feedback

The Static keyword is used in these contexts:

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Static Statement

Sub Statement


Step

 Copy code hover
[image]

Step <keyword>
Send feedback

The Step keyword is used in these contexts:

For...Next Statement

For Each...Next Statement


String

 Copy code hover
[image]

String <keyword>
Send feedback

The String keyword is used in these contexts:

String Data Type

String Function


Then

 Copy code hover
[image]

Then <keyword>
Send feedback

The Then keyword is used in these contexts:

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

If...Then...Else Statement


Time

 Copy code hover
[image]

Time <keyword>
Send feedback

The Time keyword is used in these contexts:

Time Function

Time Statement


To

 Copy code hover
[image]

To <keyword>
Send feedback

The To keyword is used in these contexts:

Dim Statement

For...Next Statement

Lock, Unlock Statements

Private Statement

Public Statement

ReDim Statement

Select Case Statement

Static Statement

Type Statement


True

 Copy code hover
[image]

True <keyword>
Send feedback

The True keyword has a value equal to -1.


WithEvents

 Copy code hover
[image]

WithEvents <keyword>
Send feedback

The WithEvents keyword is used in these contexts:

Dim Statement

Private Statement

Public Statement


Keyword Summaries

 Copy code hover
[image]

Keyword Summaries
Send feedback

In this section

  • Arrays Keyword Summary

  • Collection Object Keyword Summary

  • Compiler Directive Keyword Summary

  • Control Flow Keyword Summary

  • Conversion Keyword Summary

  • Data Types Keyword Summary

  • Dates and Times Keyword Summary

  • Directories and Files Keyword Summary

  • Errors Keyword Summary

  • Financial Keyword Summary

  • Input and Output Keyword Summary

  • Math Keyword Summary

  • Miscellaneous Keyword Summary

  • Operators Keyword Summary

  • Registry Keyword Summary

  • String Manipulation Keyword Summary

  • Variables and Constants Keyword Summary


Arrays Keyword Summary

 Copy code hover
[image]

Arrays Keyword Summary
Send feedback
Action | Keywords
Verify an array. | IsArray
Create an array. | Array
Change default lower limit. | Option Base
Declare and initialize an array. | Dim, Private, Public, ReDim, Static
Find the limits of an array. | LBound, UBound
Reinitialize an array. | Erase, ReDim


Collection Object Keyword Summary

 Copy code hover
[image]

Collection Object Keyword Summary
Send feedback
Action | Keywords
Create a Collection object. | Collection
Add an object to a collection. | Add
Remove an object from a collection. | Remove
Reference an item in a collection. | Item


Compiler Directive Keyword Summary

 Copy code hover
[image]

Compiler Directive Keyword Summary
Send feedback
Action | Keywords
Define compiler constant. | #Const
Compile selected blocks of code. | #If...Then...#Else


Control Flow Keyword Summary

 Copy code hover
[image]

Control Flow Keyword Summary
Send feedback
Action | Keywords
Branch. | GoSub...Return, GoTo, On Error, On...GoSub, On...GoTo
Exit or pause the program. | DoEvents, End, Exit, Stop
Loop. | Do...Loop, For...Next, For Each...Next, While...Wend, With
Make decisions. | Choose, If...Then...Else, Select Case, Switch
Use procedures. | Call, Function, Property Get, Property Let, Property Set, Sub


Conversion Keyword Summary

 Copy code hover
[image]

Conversion Keyword Summary
Send feedback
Action | Keywords
ANSI value to string. | Chr
String to lowercase or uppercase. | Format, LCase, Ucase
Date to serial number. | DateSerial, DateValue
Decimal number to other bases. | Hex, Oct
Number to string. | Format, Str
One data type to another. | CBool, CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CLngLng, CLngPtr, CSng, CStr, CVar, CVErr, Fix, Int
Date to day, month, weekday, or year. | Day, Month, Weekday, Year
Time to hour, minute, or second. | Hour, Minute, Second
String to ASCII value. | Asc
String to number. | Val
Time to serial number. | TimeSerial, TimeValue


Data Types Keyword Summary

 Copy code hover
[image]

Data Types Keyword Summary
Send feedback
Action | Keywords
Convert between data types. | CBool, CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CLngLng, CLngPtr, CSng, CStr, CVar, CVErr, Fix, Int
Set intrinsic data types. | Boolean, Byte, Currency, Date, Double, Integer, Long, LongLong, LongPtr, Object, Single, String, Variant (default)
Verify data types. | IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject
Note Note

CLngLng and LongLong are valid on 64-bit platforms only.


Dates and Times Keyword Summary

 Copy code hover
[image]

Dates and Times Keyword Summary
Send feedback
Action | Keywords
Get the current date or time. | Date, Now, Time
Perform date calculations. | DateAdd, DateDiff, DatePart
Return a date. | DateSerial, DateValue
Return a time. | TimeSerial, TimeValue
Set the date or time. | Date, Time
Time a process. | Timer


Directories and Files Keyword Summary

 Copy code hover
[image]

Directories and Files Keyword Summary
Send feedback
Action | Keywords
Change directory or folder. | ChDir
Change the drive. | ChDrive
Copy a file. | FileCopy
Make directory or folder. | MkDir
Remove directory or folder. | RmDir
Rename a file, directory, or folder. | Name
Return current path. | CurDir
Return file date/time stamp. | FileDateTime
Return file, directory, label attributes. | GetAttr
Return file length. | FileLen
Return file name or volume label. | Dir
Set attribute information for a file. | SetAttr


Errors Keyword Summary

 Copy code hover
[image]

Errors Keyword Summary
Send feedback
Action | Keywords
Generate run-time errors. | Clear, Error, Raise
Get error messages. | Error
Provide error information. | Err
Return Error variant. | CVErr
Trap errors during run time. | On Error, Resume
Type verification. | IsError


Financial Keyword Summary

 Copy code hover
[image]

Financial Keyword Summary
Send feedback
Action | Keywords
Calculate depreciation. | DDB, SLN, SYD
Calculate future value. | FV
Calculate interest rate. | Rate
Calculate internal rate of return. | IRR, MIRR
Calculate number of periods. | NPer
Calculate payments. | IPmt, Pmt, PPmt
Calculate present value. | NPV, PV


Input and Output Keyword Summary

 Copy code hover
[image]

Input and Output Keyword Summary
Send feedback
Action | Keywords
Access or create a file. | Open
Close files. | Close, Reset
Control output appearance. | Format, Print, Print #, Spc, Tab, Width #
Copy a file. | FileCopy
Get information about a file. | EOF, FileAttr, FileDateTime, FileLen, FreeFile, GetAttr, Loc, LOF, Seek
Manage files. | Dir, Kill, Lock, Unlock, Name
Read from a file. | Get, Input, Input #, Line Input #
Return length of a file. | FileLen
Set or get file attributes. | FileAttr, GetAttr, SetAttr
Set read-write position in a file. | Seek
Write to a file. | Print #, Put, Write #


Math Keyword Summary

 Copy code hover
[image]

Math Keyword Summary
Send feedback
Action | Keywords
Derive trigonometric functions. | Atn, Cos, Sin, Tan
General calculations. | Exp, Log, Sqr
Generate random numbers. | Randomize, Rnd
Get absolute value. | Abs
Get the sign of an expression. | Sgn
Perform numeric conversions. | Fix, Int


Miscellaneous Keyword Summary

 Copy code hover
[image]

Miscellaneous Keyword Summary
Send feedback
Action | Keywords
Process pending events. | DoEvents
Run other programs. | AppActivate, Shell
Send keystrokes to an application. | SendKeys
Sound a beep from computer. | Beep
System. | Environ
Provide a command-line string. | Command
Automation. | CreateObject, GetObject
Color. | QBColor, RGB


Operators Keyword Summary

 Copy code hover
[image]

Operators Keyword Summary
Send feedback
Action | Keywords
Arithmetic. | ^, -, *, /, \, Mod, +, &, =
Comparison. | =, <>, <, >, <=, >=, Like, Is
Logical operations. | Not, And, Or, Xor, Eqv, Imp


Registry Keyword Summary

 Copy code hover
[image]

Registry Keyword Summary
Send feedback
Action | Keywords
Delete program settings. | DeleteSetting
Read program settings. | GetSetting, GetAllSettings
Save program settings. | SaveSetting


String Manipulation Keyword Summary

 Copy code hover
[image]

String Manipulation Keyword Summary
Send feedback
Action | Keywords
Compare two strings. | StrComp
Convert strings. | StrConv
Convert to lowercase or uppercase. | Format, Lcase, Ucase
Create string of repeating character. | Space, String
Find length of a string. | Len
Format a string. | Format
Justify a string. | LSet, Rset
Manipulate strings. | InStr, Left, LTrim, Mid, Right, RTrim, Trim
Set string comparison rules. | Option Compare
Work with ASCII and ANSI values. | Asc, Chr


Variables and Constants Keyword Summary

 Copy code hover
[image]

Variables and Constants Keyword Summary
Send feedback
Action | Keywords
Assign value. | Let
Declare variables or constants. | Const, Dim, Private, Public, New, Static
Declare module as private. | Option Private Module
Get information about a variant. | IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject, TypeName, VarType
Refer to current object. | Me
Require explicit variable declarations. | Option Explicit
Set default data type. | Deftype


Methods (Visual Basic for Applications)

 Copy code hover
[image]

Methods (Visual Basic for Applications)
Send feedback

In this section

  • Add Method (Dictionary)

  • Add Method (Visual Basic for Applications)

  • AddFolders Method

  • Assert Method

  • BuildPath Method

  • Clear Method (Visual Basic for Applications)

  • Close Method (FileSystemObject object)

  • Copy Method (Visual Basic for Applications)

  • CopyFile Method

  • CopyFolder Method

  • CreateFolder Method

  • CreateTextFile Method

  • Delete Method (Visual Basic for Applications)

  • DeleteFile Method

  • DeleteFolder Method

  • DriveExists Method

  • Exists Method

  • FileExists Method

  • FolderExists Method

  • GetAbsolutePathName Method

  • GetBaseName Method

  • GetDrive Method

  • GetDriveName Method

  • GetExtensionName Method

  • GetFile Method

  • GetFileName Method (Visual Basic for Applications)

  • GetFolder Method

  • GetParentFolderName Method

  • GetSpecialFolder Method

  • GetTempName Method

  • Hide Method

  • Item Method (Visual Basic for Applications)

  • Items Method

  • Keys Method

  • Move Method (FileSystemObject object)

  • MoveFile Method

  • MoveFolder Method

  • OpenAsTextStream Method

  • OpenTextFile Method

  • Print Method

  • PrintForm Method

  • Raise Method

  • Read Method

  • ReadAll Method

  • ReadLine Method

  • Remove Method (FileSystemObject object)

  • Remove Method (Visual Basic for Applications)

  • RemoveAll Method

  • Show Method

  • Skip Method

  • SkipLine Method

  • WhatsThisMode Method

  • Write Method

  • WriteBlankLines Method

  • WriteLine Method


Add Method (Dictionary)

 Copy code hover
[image]

Add Method (Dictionary)
Send feedback

Description

Adds a key and item pair to a Dictionary object.

Syntax

object.Add key, item

The Add method has the following parts:

Part | Description
object | Required. Always the name of a Dictionary object.
key | Required. The key associated with the item being added.
item | Required. The item associated with the key being added.

Remarks

An error occurs if the key already exists.


Add Method (Visual Basic for Applications)

 Copy code hover
[image]

Add Method (Visual Basic for Applications)
Send feedback

Adds a member to a Collection object.

Syntax

object .Add item, key, before, after

The Add method syntax has the following object qualifier and named arguments:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
item | Required. An expression of any type that specifies the member to add to the collection.
key | Optional. A unique string expression that specifies a key string that can be used, instead of a positional index, to access a member of the collection.
before | Optional. An expression that specifies a relative position in the collection. The member to be added is placed in the collection before the member identified by the before argument. If a numeric expression, before must be a number from 1 to the value of the collection's Count property. If a string expression, before must correspond to the key specified when the member being referred to was added to the collection. You can specify a before position or an after position, but not both.
after | Optional. An expression that specifies a relative position in the collection. The member to be added is placed in the collection after the member identified by the after argument. If numeric, after must be a number from 1 to the value of the collection's Count property. If a string, after must correspond to the key specified when the member referred to was added to the collection. You can specify a before position or an after position, but not both.

Remarks

Whether the before or after argument is a string expression or numeric expression, it must refer to an existing member of the collection, or an error occurs.

An error also occurs if a specified key duplicates the key for an existing member of the collection.

Example

This example uses the Add method to add Inst objects (instances of a class called Class1 containing a Public variable InstanceName) to a collection called MyClasses. To see how this works, insert a class module and declare a public variable called InstanceName at module level of Class1 (type Public InstanceName) to hold the names of each instance. Leave the default name as Class1. Copy and paste the following code into the Form_Load event procedure of a form module.

VBA Copy code Copy code
Dim MyClasses As New Collection    ' Create a Collection object.
Dim Num As Integer    ' Counter for individualizing keys.
Dim Msg
Dim TheName    ' Holder for names user enters.
Do
    Dim Inst As New Class1    ' Create a new instance of Class1.
    Num = Num + 1    ' Increment Num, then get a name.
    Msg = "Please enter a name for this object." & Chr(13) _
     & "Press Cancel to see names in collection."
    TheName = InputBox(Msg, "Name the Collection Items")
    Inst.InstanceName = TheName    ' Put name in object instance.
    ' If user entered name, add it to the collection.
    If Inst.InstanceName <> "" Then
        ' Add the named object to the collection.
        MyClasses. Add item := Inst, key := CStr(Num)
    End If
    ' Clear the current reference in preparation for next one.
    Set Inst = Nothing
Loop Until TheName = ""
For Each x In MyClasses
    MsgBox x.instancename, , "Instance Name"
Next


AddFolders Method

 Copy code hover
[image]

AddFolders Method
Send feedback

Description

Adds a new Folder to a Folders collection.

Syntax

object.Add folderName

The Add method has the following parts:

Part | Description
object | Required. Always the name of a Folders collection.
folderName | Required. The name of the new Folder being added.

Remarks

An error occurs if the folderName already exists.


Assert Method

 Copy code hover
[image]

Assert Method
Send feedback

Conditionally suspends execution at the line on which the method appears.

Syntax

object .Assert booleanexpression

The Assert method syntax has the following object qualifier and argument:

Part | Description
object | Required. Always the Debug object.
booleanexpression | Required. An expression that evaluates to either True or False.

Remarks

Assert invocations work only within the development environment. When the module is compiled into an executable, the method calls on the Debug object are omitted.

All of booleanexpression is always evaluated. For example, even if the first part of an And expression evaluates False, the entire expression is evaluated.

Example

The following example shows how to use the Assert method. The example requires a form with two button controls on it. The default button names are Command1 and Command2.

When the example runs, clicking the Command1 button toggles the text on the button between 0 and 1. Clicking Command2 either does nothing or causes an assertion, depending on the value displayed on Command1. The assertion stops execution with the last statement executed, the Debug.Assert line, highlighted.

Copy code Copy code
Option Explicit
Private blnAssert As Boolean
Private intNumber As Integer

Private Sub Command1_Click()
    blnAssert = Not blnAssert
    intNumber = IIf(intNumber <> 0, 0, 1)
    Command1.Caption = intNumber
End Sub

Private Sub Command2_Click()
    Debug.Assert blnAssert
End Sub

Private Sub Form_Load()
    Command1.Caption = intNumber
    Command2.Caption = "Assert Tester"
End Sub


BuildPath Method

 Copy code hover
[image]

BuildPath Method
Send feedback

Description

Appends a name to an existing path.

Syntax

object.BuildPath(path, name)

The BuildPath method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
path | Required. Existing path to which name is appended. Path can be absolute or relative and need not specify an existing folder.
name | Required. Name being appended to the existing path.

Remarks

The BuildPath method inserts an additional path separator between the existing path and the name, only if necessary.


Clear Method (Visual Basic for Applications)

 Copy code hover
[image]

Clear Method (Visual Basic for Applications)
Send feedback

Clears all property settings of the Err object.

Syntax

object .Clear

The object is always the Err object.

Remarks

Use Clear to explicitly clear the Err object after an error has been handled, for example, when you use deferred error handling with On Error Resume Next. The Clear method is called automatically whenever any of the following statements is executed:

  • Any type of Resume statement

  • Exit Sub, Exit Function, Exit Property

  • Any On Error statement

    Note Note

    The On Error Resume Next construct may be preferable to On Error GoTo when handling errors generated during access to other objects. Checking Err after each interaction with an object removes ambiguity about which object was accessed by the code. You can be sure which object placed the error code in Err.Number, as well as which object originally generated the error (the object specified in Err.Source).

Example

This example uses the Err object's Clear method to reset the numeric properties of the Err object to zero and its string properties to zero-length strings. If Clear were omitted from the following code, the error message dialog box would be displayed on every iteration of the loop (after an error occurs) whether or not a successive calculation generated an error. You can single-step through the code to see the effect.

Copy code Copy code
Dim Result(10) As Integer    ' Declare array whose elements
            ' will overflow easily.
Dim indx
On Error Resume Next    ' Defer error trapping.
Do Until indx = 10
    ' Generate an occasional error or store result if no error.
    Result(indx) = Rnd * indx * 20000
    If Err.Number <> 0 Then
        MsgBox Err, , "Error Generated: ", Err.HelpFile, Err.HelpContext
        Err.Clear    ' Clear Err object properties.
    End If
    indx = indx + 1
Loop


Close Method (FileSystemObject object)

 Copy code hover
[image]

Close Method (FileSystemObject object)
Send feedback

Description

Closes an open TextStream file.

Syntax

object.Close

The object is always the name of a TextStream object.


Copy Method (Visual Basic for Applications)

 Copy code hover
[image]

Copy Method (Visual Basic for Applications)
Send feedback

Description

Copies a specified file or folder from one location to another.

Syntax

object.Copy destination[, overwrite]

The Copy method syntax has these parts:

Part | Description
object | Required. Always the name of a File or Folder object.
destination | Required. Destination where the file or folder is to be copied. Wildcard characters are not allowed.
overwrite | Optional. Boolean value that is True (default) if existing files or folders are to be overwritten; False if they are not.

Remarks

The results of the Copy method on a File or Folder are identical to operations performed using FileSystemObject.CopyFile or FileSystemObject.CopyFolder where the file or folder referred to by object is passed as an argument. You should note, however, that the alternative methods are capable of copying multiple files or folders.


CopyFile Method

 Copy code hover
[image]

CopyFile Method
Send feedback

Description

Copies one or more files from one location to another.

Syntax

object.CopyFile source, destination[, overwrite]

The CopyFile method syntax has these parts:

Part | Description
object | Required. The object is always the name of a FileSystemObject.
source | Required. Character string file specification, which can include wildcard characters, for one or more files to be copied.
destination | Required. Character string destination where the file or files from source are to be copied. Wildcard characters are not allowed.
overwrite | Optional. Boolean value that indicates if existing files are to be overwritten. If True, files are overwritten; if False, they are not. The default is True. Note that CopyFile will fail if destination has the read-only attribute set, regardless of the value of overwrite.

Remarks

Wildcard characters can only be used in the last path component of the source argument. For example, you can use:

Copy code Copy code
FileSystemObject.CopyFile "c:\mydocuments\letters\*.doc", "c:\tempfolder\"

But you can't use:

Copy code Copy code
FileSystemObject.CopyFile "c:\mydocuments\*\R1???97.xls", "c:\tempfolder"

If source contains wildcard characters or destination ends with a path separator (\), it is assumed that destination is an existing folder in which to copy matching files. Otherwise, destination is assumed to be the name of a file to create. In either case, three things can happen when an individual file is copied.

  • If destination does not exist, source gets copied. This is the usual case.

  • If destination is an existing file, an error occurs if overwrite is False. Otherwise, an attempt is made to copy source over the existing file.

  • If destination is a directory, an error occurs.

An error also occurs if a source using wildcard characters doesn't match any files. The CopyFile method stops on the first error it encounters. No attempt is made to roll back or undo any changes made before an error occurs.


CopyFolder Method

 Copy code hover
[image]

CopyFolder Method
Send feedback

Description

Recursively copies a folder from one location to another.

Syntax

object.CopyFolder source, destination[, overwrite]

The CopyFolder method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
source | Required. Character string folder specification, which can include wildcard characters, for one or more folders to be copied.
destination | Required. Character string destination where the folder and subfolders from source are to be copied. Wildcard characters are not allowed.
overwrite | Optional. Boolean value that indicates if existing folders are to be overwritten. If True, files are overwritten; if False, they are not. The default is True.

Remarks

Wildcard characters can only be used in the last path component of the source argument. For example, you can use:

Copy code Copy code
FileSystemObject.CopyFolder "c:\mydocuments\letters\*", "c:\tempfolder\"

But you can't use:

Copy code Copy code
FileSystemObject.CopyFolder "c:\mydocuments\*\*", "c:\tempfolder\"

If source contains wildcard characters or destination ends with a path separator (\), it is assumed that destination is an existing folder in which to copy matching folders and subfolders. Otherwise, destination is assumed to be the name of a folder to create. In either case, four things can happen when an individual folder is copied.

  • If destination does not exist, the source folder and all its contents gets copied. This is the usual case.

  • If destination is an existing file, an error occurs.

  • If destination is a directory, an attempt is made to copy the folder and all its contents. If a file contained in source already exists in destination, an error occurs if overwrite is False. Otherwise, it will attempt to copy the file over the existing file.

  • If destination is a read-only directory, an error occurs if an attempt is made to copy an existing read-only file into that directory and overwrite is False.

An error also occurs if a source using wildcard characters doesn't match any folders.

The CopyFolder method stops on the first error it encounters. No attempt is made to roll back any changes made before an error occurs.


CreateFolder Method

 Copy code hover
[image]

CreateFolder Method
Send feedback

Description

Creates a folder.

Syntax

object.CreateFolder(foldername)

The CreateFolder method has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
foldername | Required. String expression that identifies the folder to create.

Remarks

An error occurs if the specified folder already exists.


CreateTextFile Method

 Copy code hover
[image]

CreateTextFile Method
Send feedback

Description

Creates a specified file name and returns a TextStream object that can be used to read from or write to the file.

Syntax

object.CreateTextFile(filename[, overwrite[, unicode]])

The CreateTextFile method has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject or Folder object.
filename | Required. String expression that identifies the file to create.
overwrite | Optional. Boolean value that indicates if an existing file can be overwritten. The value is True if the file can be overwritten; False if it can't be overwritten. If omitted, existing files are not overwritten.
unicode | Optional. Boolean value that indicates whether the file is created as a Unicode or ASCII file. The value is True if the file is created as a Unicode file; False if it's created as an ASCII file. If omitted, an ASCII file is assumed.

Remarks

The following code illustrates how to use the CreateTextFile method to create and open a text file:

If the overwrite argument is False, or is not provided, for a filename that already exists, an error occurs.

Copy code Copy code
Sub CreateAfile
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set a = fs.CreateTextFile("c:\testfile.txt", True)
    a.WriteLine("This is a test.")
    a.Close
End Sub


Delete Method (Visual Basic for Applications)

 Copy code hover
[image]

Delete Method (Visual Basic for Applications)
Send feedback

Description

Deletes a specified file or folder.

Syntax

object.Delete force

The Delete method syntax has these parts:

Part | Description
object | Required. Always the name of a File or Folder object.
force | Optional. Boolean value that is True if files or folders with the read-only attribute set are to be deleted; False (default) if they are not.

Remarks

An error occurs if the specified file or folder does not exist.

The results of the Delete method on a File or Folder are identical to operations performed using FileSystemObject.DeleteFile or FileSystemObject.DeleteFolder.

The Delete method does not distinguish between folders that have contents and those that do not. The specified folder is deleted regardless of whether or not it has contents.


DeleteFile Method

 Copy code hover
[image]

DeleteFile Method
Send feedback

Description

Deletes a specified file.

Syntax

object.DeleteFile filespec[, force]

The DeleteFile method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
filespec | Required. The name of the file to delete. The filespec can contain wildcard characters in the last path component.
force | Optional. Boolean value that is True if files with the read-only attribute set are to be deleted; False (default) if they are not.

Remarks

An error occurs if no matching files are found. The DeleteFile method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred.


DeleteFolder Method

 Copy code hover
[image]

DeleteFolder Method
Send feedback

Description

Deletes a specified folder and its contents.

Syntax

object.DeleteFolder folderspec[, force]

The DeleteFolder method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
folderspec | Required. The name of the folder to delete. The folderspec can contain wildcard characters in the last path component.
force | Optional. Boolean value that is True if folders with the read-only attribute set are to be deleted; False (default) if they are not.

Remarks

The DeleteFolder method does not distinguish between folders that have contents and those that do not. The specified folder is deleted regardless of whether or not it has contents.

An error occurs if no matching folders are found. The DeleteFolder method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred.


DriveExists Method

 Copy code hover
[image]

DriveExists Method
Send feedback

Description

Returns True if the specified drive exists; False if it does not.

Syntax

object.DriveExists(drivespec)

The DriveExists method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
drivespec | Required. A drive letter or a complete path specification.

Remarks

For drives with removable media, the DriveExists method returns True even if there are no media present. Use the IsReady property of the Drive object to determine if a drive is ready.


Exists Method

 Copy code hover
[image]

Exists Method
Send feedback

Description

Returns True if a specified key exists in the Dictionary object; False if it does not.

Syntax

object.Exists(key)

The Exists method syntax has these parts:

Part | Description
object | Required. Always the name of a Dictionary object.
key | Required. Key value being searched for in the Dictionary object.


FileExists Method

 Copy code hover
[image]

FileExists Method
Send feedback

Description

Returns True if a specified file exists; False if it does not.

Syntax

object.FileExists(filespec)

The FileExists method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
filespec | Required. The name of the file whose existence is to be determined. A complete path specification (either absolute or relative) must be provided if the file isn't expected to exist in the current folder.


FolderExists Method

 Copy code hover
[image]

FolderExists Method
Send feedback

Description

Returns True if a specified folder exists; False if it does not.

Syntax

object.FolderExists(folderspec)

The FolderExists method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
folderspec | Required. The name of the folder whose existence is to be determined. A complete path specification (either absolute or relative) must be provided if the folder isn't expected to exist in the current folder.


GetAbsolutePathName Method

 Copy code hover
[image]

GetAbsolutePathName Method
Send feedback

Description

Returns a complete and unambiguous path from a provided path specification.

Syntax

object.GetAbsolutePathName(pathspec)

The GetAbsolutePathName method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
pathspec | Required. Path specification to change to a complete and unambiguous path.

Remarks

A path is complete and unambiguous if it provides a complete reference from the root of the specified drive. A complete path can only end with a path separator character (\) if it specifies the root folder of a mapped drive.

Assuming the current directory is c:\mydocuments\reports, the following table illustrates the behavior of the GetAbsolutePathName method.

pathspec | Returned path
"c:" | "c:\mydocuments\reports"
"c:.." | "c:\mydocuments"
"c:\\\" | "c:\"
"c:*.*\may97" | "c:\mydocuments\reports\*.*\may97"
"region1" | "c:\mydocuments\reports\region1"
"c:\..\..\mydocuments" | "c:\mydocuments"


GetBaseName Method

 Copy code hover
[image]

GetBaseName Method
Send feedback

Description

Returns a string containing the base name of the last component, less any file extension, in a path.

Syntax

object.GetBaseName(path)

The GetBaseName method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
path | Required. The path specification for the component whose base name is to be returned.

Remarks

The GetBaseName method returns a zero-length string ("") if no component matches the path argument.

Note Note

The GetBaseName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.


GetDrive Method

 Copy code hover
[image]

GetDrive Method
Send feedback

Description

Returns a Drive object corresponding to the drive in a specified path.

Syntax

object.GetDrive drivespec

The GetDrive method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
drivespec | Required. The drivespec argument can be a drive letter (c), a drive letter with a colon appended (c:), a drive letter with a colon and path separator appended (c:\), or any network share specification (\\computer2\share1).

Remarks

For network shares, a check is made to ensure that the share exists.

An error occurs if drivespec does not conform to one of the accepted forms or does not exist.

To call the GetDrive method on a normal path string, use the following sequence to get a string that is suitable for use as drivespec:

Copy code Copy code
DriveSpec = GetDriveName(GetAbsolutePathName(Path))


GetDriveName Method

 Copy code hover
[image]

GetDriveName Method
Send feedback

Description

Returns a string containing the name of the drive for a specified path.

Syntax

object.GetDriveName(path)

The GetDriveName method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
path | Required. The path specification for the component whose drive name is to be returned.

Remarks

The GetDriveName method returns a zero-length string ("") if the drive can't be determined.

Note Note

The GetDriveName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.


GetExtensionName Method

 Copy code hover
[image]

GetExtensionName Method
Send feedback

Description

Returns a string containing the extension name for the last component in a path.

Syntax

object.GetExtensionName(path)

The GetExtensionName method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
path | Required. The path specification for the component whose extension name is to be returned.

Remarks

For network drives, the root directory (\) is considered to be a component.

The GetExtensionName method returns a zero-length string ("") if no component matches the path argument.


GetFile Method

 Copy code hover
[image]

GetFile Method
Send feedback

Description

Returns a File object corresponding to the file in a specified path.

Syntax

object.GetFile(filespec)

The GetFile method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
filespec | Required. The filespec is the path (absolute or relative) to a specific file.

Remarks

An error occurs if the specified file does not exist.


GetFileName Method (Visual Basic for Applications)

 Copy code hover
[image]

GetFileName Method (Visual Basic for Applications)
Send feedback

Description

Returns the last component of specified path that is not part of the drive specification.

Syntax

object.GetFileName(pathspec)

The GetFileName method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
pathspec | Required. The path (absolute or relative) to a specific file.

Remarks

The GetFileName method returns a zero-length string ("") if pathspec does not end with the named component.

Note Note

The GetFileName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.


GetFolder Method

 Copy code hover
[image]

GetFolder Method
Send feedback

Description

Returns a Folder object corresponding to the folder in a specified path.

Syntax

object.GetFolder(folderspec)

The GetFolder method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
folderspec | Required. The folderspec is the path (absolute or relative) to a specific folder.

Remarks

An error occurs if the specified folder does not exist.


GetParentFolderName Method

 Copy code hover
[image]

GetParentFolderName Method
Send feedback

Description

Returns a string containing the name of the parent folder of the last component in a specified path.

Syntax

object.GetParentFolderName(path)

The GetParentFolderName method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
path | Required. The path specification for the component whose parent folder name is to be returned.

Remarks

The GetParentFolderName method returns a zero-length string ("") if there is no parent folder for the component specified in the path argument.

Note Note

The GetParentFolderName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.


GetSpecialFolder Method

 Copy code hover
[image]

GetSpecialFolder Method
Send feedback

Description

Returns the special folder specified.

Syntax

object .GetSpecialFolder( folderspec )

The GetSpecialFolder method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
folderspec | Required. The name of the special folder to be returned. Can be any of the constants shown in the Settings section.

Settings

The folderspec argument can have any of the following values:

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


GetTempName Method

 Copy code hover
[image]

GetTempName Method
Send feedback

Description

Returns a randomly generated temporary file or folder name that is useful for performing operations that require a temporary file or folder.

Syntax

object.GetTempName

The optional object is always the name of a FileSystemObject.

Remarks

The GetTempName method does not create a file. It provides only a temporary file name that can be used with CreateTextFile to create a file.


Hide Method

 Copy code hover
[image]

Hide Method
Send feedback

Hides an object but doesn't unload it.

Syntax

object.Hide

The object placeholder represents an object expression that evaluates to an object in the Applies To list. If object is omitted, the UserForm with the focus is assumed to be object.

Remarks

When an object is hidden, it's removed from the screen and its Visible property is set to False. A hidden object's controls aren't accessible to the user, but they are available programmatically to the running application, to other processes that may be communicating with the application through Automation, and in Windows, to Timer control events.

When a UserForm is hidden, the user can't interact with the application until all code in the event procedure that caused the UserForm to be hidden has finished executing.

If the UserForm isn't loaded when the Hide method is invoked, the Hide method loads the UserForm but doesn't display it.

Example

The following example assumes two UserForms in a program. In UserForm1's Initialize event, UserForm2 is loaded and shown. When the user clicks UserForm2, it is hidden and UserForm1 appears. When UserForm1 is clicked, UserForm2 is shown again.

Copy code Copy code
' This is the Initialize event procedure for UserForm1
Private Sub UserForm_Initialize()
    Load UserForm2
    UserForm2.Show
End Sub
' This is the Click event of UserForm2
Private Sub UserForm_Click()
    UserForm2.Hide
End Sub

' This is the click event for UserForm1
Private Sub UserForm_Click()
    UserForm2.Show
End Sub


Item Method (Visual Basic for Applications)

 Copy code hover
[image]

Item Method (Visual Basic for Applications)
Send feedback

Returns a specific member of a Collection object either by position or by key.

Syntax

object .Item( index )

The Item method syntax has the following object qualifier and part:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
index | Required. An expression that specifies the position of a member of the collection. If a numeric expression, index must be a number from 1 to the value of the collection's Count property. If a string expression, index must correspond to the key argument specified when the member referred to was added to the collection.

Remarks

If the value provided as index doesn't match any existing member of the collection, an error occurs.

The Item method is the default method for a collection. Therefore, the following lines of code are equivalent:

VBA Copy code Copy code
Print MyCollection(1)
Print MyCollection.Item(1)

Example

This example uses the Item method to retrieve a reference to an object in a collection. Assuming Birthdays is a Collection object, the following code retrieves from the collection references to the objects representing Bill Smith's birthday and Adam Smith's birthday, using the keys "SmithBill" and "SmithAdam" as the index arguments. Note that the first call explicitly specifies the Item method, but the second does not. Both calls work because the Item method is the default for a Collection object. The references, assigned to SmithBillBD and SmithAdamBD using Set, can be used to access the properties and methods of the specified objects. To run this code, create the collection and populate it with at least the two referenced members.

VBA Copy code Copy code
Dim SmithBillBD As Object
Dim SmithAdamBD As Object
Dim Birthdays
Set SmithBillBD = Birthdays.Item("SmithBill")
Set SmithAdamBD = Birthdays("SmithAdam")


Items Method

 Copy code hover
[image]

Items Method
Send feedback

Description

Returns an array containing all the items in a Dictionary object.

Syntax

object.Items

The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the Items method:

Copy code Copy code
Dim a, d, i             'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Items             'Get the items
For i = 0 To d.Count -1 'Iterate the array
    Print a(i)          'Print item
Next
...


Keys Method

 Copy code hover
[image]

Keys Method
Send feedback

Description

Returns an array containing all existing keys in a Dictionary object.

Syntax

object.Keys

The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the Keys method:

Copy code Copy code
Dim a, d, i             'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.keys              'Get the keys
For i = 0 To d.Count -1 'Iterate the array
    Print a(i)          'Print key
Next
...


Move Method (FileSystemObject object)

 Copy code hover
[image]

Move Method (FileSystemObject object)
Send feedback

Description

Moves a specified file or folder from one location to another.

Syntax

object.Move destination

The Move method syntax has these parts:

Part | Description
object | Required. Always the name of a File or Folder object.
destination | Required. Destination where the file or folder is to be moved. Wildcard characters are not allowed.

Remarks

The results of the Move method on a File or Folder are identical to operations performed using FileSystemObject.MoveFile or FileSystemObject.MoveFolder. You should note, however, that the alternative methods are capable of moving multiple files or folders.


MoveFile Method

 Copy code hover
[image]

MoveFile Method
Send feedback

Description

Moves one or more files from one location to another.

Syntax

object.MoveFile source, destination

The MoveFile method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
source | Required. The path to the file or files to be moved. The source argument string can contain wildcard characters in the last path component only.
destination | Required. The path where the file or files are to be moved. The destination argument can't contain wildcard characters.

Remarks

If source contains wildcards or destination ends with a path separator (\), it is assumed that destination specifies an existing folder in which to move the matching files. Otherwise, destination is assumed to be the name of a destination file to create. In either case, three things can happen when an individual file is moved:

  • If destination does not exist, the file gets moved. This is the usual case.

  • If destination is an existing file, an error occurs.

  • If destination is a directory, an error occurs.

An error also occurs if a wildcard character that is used in source doesn't match any files. The MoveFile method stops on the first error it encounters. No attempt is made to roll back any changes made before the error occurs.

Important note Important

This method allows moving files between volumes only if supported by the operating system.


MoveFolder Method

 Copy code hover
[image]

MoveFolder Method
Send feedback

Description

Moves one or more folders from one location to another.

Syntax

object.MoveFolder source, destination

The MoveFolder method syntax has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
source | Required. The path to the folder or folders to be moved. The source argument string can contain wildcard characters in the last path component only.
destination | Required. The path where the folder or folders are to be moved. The destination argument can't contain wildcard characters.

Remarks

If source contains wildcards or destination ends with a path separator (\), it is assumed that destination specifies an existing folder in which to move the matching files. Otherwise, destination is assumed to be the name of a destination folder to create. In either case, three things can happen when an individual folder is moved:

  • If destination does not exist, the folder gets moved. This is the usual case.

  • If destination is an existing file, an error occurs.

  • If destination is a directory, an error occurs.

An error also occurs if a wildcard character that is used in source doesn't match any folders. The MoveFolder method stops on the first error it encounters. No attempt is made to roll back any changes made before the error occurs.

Important note Important

This method allows moving folders between volumes only if supported by the operating system.


OpenAsTextStream Method

 Copy code hover
[image]

OpenAsTextStream Method
Send feedback

Description

Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.

Syntax

object.OpenAsTextStream([iomode, [format]])

The OpenAsTextStream method syntax has these parts:

Part | Description
object | Required. Always the name of a File object.
iomode | Optional. Indicates input/output mode. Can be one of three constants: ForReading, ForWriting, or ForAppending.
format | Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.

Settings

The iomode argument can have any of the following settings:

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

The format argument can have any of the following settings:

Constant | Value | Description
TristateUseDefault | -2 | Opens the file using the system default.
TristateTrue | -1 | Opens the file as Unicode.
TristateFalse | 0 | Opens the file as ASCII.

Remarks

The OpenAsTextStream method provides the same functionality as the OpenTextFile method of the FileSystemObject. In addition, the OpenAsTextStream method can be used to write to a file.

The following code illustrates the use of the OpenAsTextStream method:

Copy code Copy code
Sub TextStreamTest
    Const ForReading = 1, ForWriting = 2, ForAppending = 3
    Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
    Dim fs, f, ts, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    fs.CreateTextFile "test1.txt"            'Create a file
    Set f = fs.GetFile("test1.txt")
    Set ts = f.OpenAsTextStream(ForWriting, TristateUseDefault)
    ts.Write "Hello World"
    ts.Close
    Set ts = f.OpenAsTextStream(ForReading, TristateUseDefault)
    s = ts.ReadLine
    MsgBox s
    ts.Close
End Sub


OpenTextFile Method

 Copy code hover
[image]

OpenTextFile Method
Send feedback

Description

Opens a specified file and returns a TextStream object that can be used to read from or append to the file.

Syntax

object.OpenTextFile(filename[, iomode[, create[, format]]])

The OpenTextFile method has these parts:

Part | Description
object | Required. Always the name of a FileSystemObject.
filename | Required. String expression that identifies the file to open.
iomode | Optional. Indicates input/output mode. Can be one of two constants, either ForReading or ForAppending.
create | Optional. Boolean value that indicates whether a new file can be created if the specified filename doesn't exist. The value is True if a new file is created; False if it isn't created. The default is False.
format | Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.

Settings

The iomode argument can have either of the following settings:

Constant | Value | Description
ForReading | 1 | Open a file for reading only. You can't write to this file.
ForAppending | 8 | Open a file and write to the end of the file.

The format argument can have any of the following settings:

Constant | Value | Description
TristateUseDefault | -2 | Opens the file using the system default.
TristateTrue | -1 | Opens the file as Unicode.
TristateFalse | 0 | Opens the file as ASCII.

Remarks

The following code illustrates the use of the OpenTextFile method to open a file for appending text:

Copy code Copy code
Sub OpenTextFileTest
    Const ForReading = 1, ForWriting = 2, ForAppending = 3
    Dim fs, f
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.OpenTextFile("c:\testfile.txt", ForAppending,TristateFalse)
    f.Write "Hello world!"
    f.Close
End Sub


Print Method

 Copy code hover
[image]

Print Method
Send feedback

Prints text in the Immediate window.

Syntax

object .Print [outputlist]

The Print method syntax has the following object qualifier and part:

Part | Description
object | Optional. An object expression that evaluates to an object in the Applies To list.
outputlist | Optional. Expression or list of expressions to print. If omitted, a blank line is printed.

The outputlist argument has the following syntax and parts:

{Spc(n) | Tab(n)} expression charpos

Part | Description
Spc( n ) | Optional. Used to insert space characters in the output, where n is the number of space characters to insert.
Tab( n ) | Optional. Used to position the insertion point at an absolute column number where n is the column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone.
expression | Optional. Numeric expression or string expression to print.
charpos | Optional. Specifies the insertion point for the next character. Use a semicolon (;) to position the insertion point immediately following the last character displayed. Use Tab(n) to position the insertion point at an absolute column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone. If charpos is omitted, the next character is printed on the next line.

Remarks

Multiple expressions can be separated with either a space or a semicolon.

All data printed to the Immediate window is properly formatted using the decimal separator for the locale settings specified for your system. The keywords are output in the appropriate language for the host application.

For Boolean data, either True or False is printed. The True and False keywords are translated according to the locale setting for the host application.

Date data is written using the standard short date format recognized by your system. When either the date or the time component is missing or zero, only the data provided is written.

Nothing is written if outputlist data is Empty. However, if outputlist data is Null, Null is output. The Null keyword is appropriately translated when it is output.

For error data, the output is written as Error errorcode. The Error keyword is appropriately translated when it is output.

The object is required if the method is used outside a module having a default display space. For example an error occurs if the method is called in a standard module without specifying an object, but if called in a form module, outputlist is displayed on the form.

Note Note

Because the Print method typically prints with proportionally-spaced characters, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, a wide letter, such as a "W", occupies more than one fixed-width column, and a narrow letter, such as an "i", occupies less. To allow for cases where wider than average characters are used, your tabular columns must be positioned far enough apart. Alternatively, you can print using a fixed-pitch font (such as Courier) to ensure that each character uses only one column.

Example

Using the Print method, this example displays the value of the variable MyVar in the Immediate window. Note that the Print method only applies to objects that can display text.

VBA Copy code Copy code
Dim MyVar
MyVar = "Come see me in the Immediate pane."
Debug.Print MyVar


PrintForm Method

 Copy code hover
[image]

PrintForm Method
Send feedback

Sends a bit-by-bit image of a UserForm object to the printer.

Syntax

object .PrintForm

The object placeholder represents an object expression that evaluates to an object in the Applies To list. If object is omitted, the UserForm with the focus is assumed to be object.

Remarks

PrintForm prints all visible objects and bitmaps of the UserForm object. PrintForm also prints graphics added to a UserForm object.

The printer used by PrintForm is determined by the operating system's Control Panel settings.

Example

In the following example, the client area of the form is printed when the user clicks the form.

Copy code Copy code
' This is the click event for UserForm1
Private Sub UserForm_Click()
    UserForm1.PrintForm
End Sub


Raise Method

 Copy code hover
[image]

Raise Method
Send feedback

Generates a run-time error.

Syntax

object .Raise number, source, description, helpfile, helpcontext

The Raise method has the following object qualifier and named arguments:

Argument | Description
object | Required. Always the Err object.
number | Required. Long integer that identifies the nature of the error. Visual Basic errors (both Visual Basic-defined and user-defined errors) are in the range 0-65535. The range 0-512 is reserved for system errors; the range 513-65535 is available for user-defined errors. When setting the Number property to your own error code in a class module, you add your error code number to the vbObjectError constant. For example, to generate the error number 513, assign vbObjectError + 513 to the Number property.
source | Optional. String expression naming the object or application that generated the error. When setting this property for an object, use the form project.class. If source is not specified, the programmatic ID of the current Visual Basic project is used.
description | Optional. String expression describing the error. If unspecified, the value in Number is examined. If it can be mapped to a Visual Basic run-time error code, the string that would be returned by the Error function is used as Description. If there is no Visual Basic error corresponding to Number, the "Application-defined or object-defined error" message is used.
helpfile | Optional. The fully qualified path to the Help file in which help on this error can be found. If unspecified, Visual Basic uses the fully qualified drive, path, and file name of the Visual Basic Help file.
helpcontext | Optional. The context ID identifying a topic within helpfile that provides help for the error. If omitted, the Visual Basic Help file context ID for the error corresponding to the Number property is used, if it exists.

Remarks

All of the arguments are optional except number. If you use Raise without specifying some arguments, and the property settings of the Err object contain values that have not been cleared, those values serve as the values for your error.

Raise is used for generating run-time errors and can be used instead of the Error statement. Raise is useful for generating errors when writing class modules, because the Err object gives richer information than is possible if you generate errors with the Error statement. For example, with the Raise method, the source that generated the error can be specified in the Source property, online Help for the error can be referenced, and so on.

Example

This example uses the Err object's Raise method to generate an error within an Automation object written in Visual Basic. It has the programmatic ID MyProj.MyObject. On the MacIntosh, the default drive name is "HD" and portions of the pathname are separated by colons instead of backslashes.

Copy code Copy code
Const MyContextID = 1010407    ' Define a constant for contextID.
Function TestName(CurrentName, NewName)
    If Instr(NewName, "bob") Then    ' Test the validity of NewName.
        ' Raise the exception
        Err.Raise vbObjectError + 513, "MyProj.MyObject", _
        "No ""bob"" allowed in your name", "c:\MyProj\MyHelp.Hlp", _
        MyContextID
    End If
End Function


Read Method

 Copy code hover
[image]

Read Method
Send feedback

Description

Reads a specified number of characters from a TextStream file and returns the resulting string.

Syntax

object.Read(characters)

The Read method syntax has these parts:

Part | Description
object | Required. Always the name of a TextStreamobject.
characters | Required. Number of characters you want to read from the file.


ReadAll Method

 Copy code hover
[image]

ReadAll Method
Send feedback

Description

Reads an entire TextStream file and returns the resulting string.

Syntax

object.ReadAll

The object is always the name of a TextStream object.

Remarks

For large files, using the ReadAll method wastes memory resources. Other techniques should be used to input a file, such as reading a file line by line.


ReadLine Method

 Copy code hover
[image]

ReadLine Method
Send feedback

Description

Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.

Syntax

object.ReadLine

The object argument is always the name of a TextStream object.


Remove Method (FileSystemObject object)

 Copy code hover
[image]

Remove Method (FileSystemObject object)
Send feedback

Description

Removes a key, item pair from a Dictionary object.

Syntax

object.Remove(key)

The Remove method syntax has these parts:

Part | Description
object | Required. Always the name of a Dictionary object.
key | Required. Key associated with the key, item pair you want to remove from the Dictionary object.

Remarks

An error occurs if the specified key, item pair does not exist.

The following code illustrates use of the Remove method:

Copy code Copy code
Dim a, d, i             'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
a = d. Remove()          'Remove second pair


Remove Method (Visual Basic for Applications)

 Copy code hover
[image]

Remove Method (Visual Basic for Applications)
Send feedback

Removes a member from a Collection object.

Syntax

object .Remove index

The Remove method syntax has the following object qualifier and part:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
index | Required. An expression that specifies the position of a member of the collection. If a numeric expression, index must be a number from 1 to the value of the collection's Count property. If a string expression, index must correspond to the key argument specified when the member referred to was added to the collection.

Remarks

If the value provided as index doesn't match an existing member of the collection, an error occurs.

Example

This example illustrates the use of the Remove method to remove objects from a Collection object, MyClasses. This code removes the object whose index is 1 on each iteration of the loop.

Copy code Copy code
Dim Num, MyClasses
For Num = 1 To MyClasses.Count
    MyClasses.Remove 1    ' Remove the first object each time
            ' through the loop until there are
            ' no objects left in the collection.
Next Num


RemoveAll Method

 Copy code hover
[image]

RemoveAll Method
Send feedback

Description

The RemoveAll method removes all key, item pairs from a Dictionary object.

Syntax

object.RemoveAll

The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the RemoveAll method:

Copy code Copy code
Dim a, d, i             'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
a = d.RemoveAll         'Clear the dictionary


Show Method

 Copy code hover
[image]

Show Method
Send feedback

Displays a UserForm object.

Syntax

[object.]Show modal

The Show method syntax has these parts:

Part | Description
object | Optional. An object expression that evaluates to an object in the Applies To list. If object is omitted, the UserForm associated with the active UserForm module is assumed to be object.
modal | Optional. Boolean value that determines if the UserForm is modal or modeless.

Settings

The settings for modal are:

Constant | Value | Description
vbModal | 1 | UserForm is modal. Default.
vbModeless | 0 | UserForm is modeless.

Remarks

If the specified object isn't loaded when the Show method is invoked, Visual Basic automatically loads it.

Note Note

In Microsoft Office 97, if a UserForm is set to display as modeless, it causes a run-time error; Office 97 UserForms are always modal.

When a UserForm is modeless, subsequent code is executed as it's encountered. Modeless forms do not appear in the task bar and are not in the window tab order.

Note Note

You may lose data associated with a modeless UserForm if you make a change to the UserForm project that causes it to recompile, for example, removing a code module.

When a UserForm is modal, the user must respond before using any other part of the application. No subsequent code is executed until the UserForm is hidden or unloaded. Although other forms in the application are disabled when a UserForm is displayed, other applications are not.

Example

The following example assumes two UserForms in a program. In UserForm1's Initialize event, UserForm2 is loaded and shown. When the user clicks UserForm2, it is hidden and UserForm1 appears. When UserForm1 is clicked, UserForm2 is shown again.

Copy code Copy code
' This is the Initialize event procedure for UserForm1
Private Sub UserForm_Initialize()
    Load UserForm2
    UserForm2.Show
End Sub
' This is the Click event for UserForm2
Private Sub UserForm_Click()
    UserForm2.Hide
End Sub

' This is the click event for UserForm1
Private Sub UserForm_Click()
    UserForm2.Show
End Sub


Skip Method

 Copy code hover
[image]

Skip Method
Send feedback

Description

Skips a specified number of characters when reading a TextStream file.

Syntax

object.Skip(characters)

The Skip method syntax has these parts:

Part | Description
object | Required. Always the name of a TextStream object.
characters | Required. Number of characters to skip when reading a file.

Remarks

Skipped characters are discarded.


SkipLine Method

 Copy code hover
[image]

SkipLine Method
Send feedback

Description

Skips the next line when reading a TextStream file.

Syntax

object.SkipLine

The object is always the name of a TextStream object.

Remarks

Skipping a line means reading and discarding all characters in a line up to and including the next newline character.

An error occurs if the file is not open for reading.


WhatsThisMode Method

 Copy code hover
[image]

WhatsThisMode Method
Send feedback

Causes the mouse pointer to change to the What's This pointer and prepares the application to display Help on a selected object. This method exists on the Macintosh, but there is no pointer functionality.

Syntax

object.WhatsThisMode

The object placeholder represents an object expression that evaluates to an object in the Applies To list. If object is omitted, the UserForm with the focus is assumed to be object.

Remarks

Executing the WhatsThisMode method places the application in the same state as clicking the What's This button on the title bar. The mouse pointer changes to the What's This pointer. When the user clicks an object, the WhatsThisHelpID property of the clicked object is used to invoke the context-sensitive Help.

Example

The following example changes the mouse pointer to the What's This (question mark) pointer when the user clicks the UserForm. If neither the WhatsThisHelp or the WhatsThisButton property is set to True in the Properties window, the following invocation has no effect.

Copy code Copy code
Private Sub UserForm_Click()
' Turn mouse pointer to What's This question mark.
    WhatsThisMode
End Sub


Write Method

 Copy code hover
[image]

Write Method
Send feedback

Description

Writes a specified string to a TextStream file.

Syntax

object.Write(string)

The Write method syntax has these parts:

Part | Description
object | Required. Always the name of a TextStream object.
string | Required. The text you want to write to the file.

Remarks

Specified strings are written to the file with no intervening spaces or characters between each string. Use the WriteLine method to write a newline character or a string that ends with a newline character.


WriteBlankLines Method

 Copy code hover
[image]

WriteBlankLines Method
Send feedback

Description

Writes a specified number of newline characters to a TextStream file.

Syntax

object.WriteBlankLines(lines)

The WriteBlankLines method syntax has these parts:

Part | Description
object | Required. Always the name of a TextStream object.
lines | Required. Number of newline characters you want to write to the file.


WriteLine Method

 Copy code hover
[image]

WriteLine Method
Send feedback

Description

Writes a specified string and newline character to a TextStream file.

Syntax

object.WriteLine([string])

The WriteLine method syntax has these parts:

Part | Description
object | Required. Always the name of a TextStream object.
string | Optional. The text you want to write to the file. If omitted, a newline character is written to the file.


Object Browser (Visual Basic for Applications)

 Copy code hover
[image]

Object Browser (Visual Basic for Applications)
Send feedback

In this section

  • Collection (Object Browser)

  • Constants (Object Browser)

  • Conversion (Object Browser)

  • DateTime (Object Browser)

  • ErrObject (Object Browser)

  • FileSystem (Object Browser)

  • Financial (Object Browser)

  • Global (Object Browser)

  • Information (Object Browser)

  • Interaction (Object Browser)

  • Math (Object Browser)

  • String (Object Browser)

  • VbAppWinStyle (Object Browser)

  • VbCalendar (Object Browser)

  • VbCallType (Object Browser)

  • VbCompareMethod (Object Browser)

  • VbDateTimeFormat (Object Browser)

  • VbDayOfWeek (Object Browser)

  • VbFileAttribute (Object Browser)

  • VbFirstWeekOfYear (Object Browser)

  • VbIMEStatus (Object Browser)

  • VbMsgBoxResult (Object Browser)

  • VbMsgBoxStyle (Object Browser)

  • VbQueryClose (Object Browser)

  • VbStrConv (Object Browser)

  • VbTriState (Object Browser)

  • VbVarType (Object Browser)


Collection (Object Browser)

 Copy code hover
[image]

Collection (Object Browser)
Send feedback

The Collection module contains procedures used to perform operations on the Collection object. These constants can be used anywhere in your code.

To get Help on a particular procedure

  1. Select the procedure from the Members of 'Collection' list.

  2. Click the [image] button.


Constants (Object Browser)

 Copy code hover
[image]

Constants (Object Browser)
Send feedback

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

To get Help on a particular constant

  1. Select the constant from the Members of 'Constants' list.

  2. Click the [image] button.


Conversion (Object Browser)

 Copy code hover
[image]

Conversion (Object Browser)
Send feedback

The Conversion module contains the procedures used to perform various conversion operations. These constants can be used anywhere in your code.

To get Help on a particular procedure

  1. Select the procedure from the Members of 'Conversion' list.

  2. Click the [image] button.

    Note Note

    When you use Variant variables, explicit data-type conversions are unnecessary.


DateTime (Object Browser)

 Copy code hover
[image]

DateTime (Object Browser)
Send feedback

The DateTime module contains the procedures and properties used in date and time operations. These constants can be used anywhere in your code.

To get Help on a particular procedure or property

  1. Select the procedure from the Members of 'DateTime' list.

  2. Click the [image] button.


ErrObject (Object Browser)

 Copy code hover
[image]

ErrObject (Object Browser)
Send feedback

The ErrObject module contains properties and procedures used to identify and handle run-time errors using the Err object. These constants can be used anywhere in your code.

To get Help on a particular property or procedure

  1. Select the property or procedure from the Members of 'ErrObject' list.

  2. Click the [image] button.


FileSystem (Object Browser)

 Copy code hover
[image]

FileSystem (Object Browser)
Send feedback

The FileSystem module contains the procedures used to perform file, directory or folder, and system operations. These constants can be used anywhere in your code.

To get Help on a particular procedure

  1. Select the procedure from the Members of 'FileSystem' list.

  2. Click the [image] button.


Financial (Object Browser)

 Copy code hover
[image]

Financial (Object Browser)
Send feedback

The Financial module contains procedures used to perform financial operations. These constants can be used anywhere in your code.

To get Help on a particular procedure

  1. Select the procedure from the Members of 'Financial' list.

  2. Click the [image] button.


Global (Object Browser)

 Copy code hover
[image]

Global (Object Browser)
Send feedback

The Global module contains procedures and properties used to perform operations on the UserForm object. These constants can be used anywhere in your code.

To get Help on a particular property or procedure

  1. Select the procedure from the Members Of 'Global' list.

  2. Click the [image] button.


Information (Object Browser)

 Copy code hover
[image]

Information (Object Browser)
Send feedback

The Information module contains the procedures used to return, test for, or verify information. These constants can be used anywhere in your code.

To get Help on a particular procedure

  1. Select the procedure from the Members of 'Information' list.

  2. Click the [image] button.


Interaction (Object Browser)

 Copy code hover
[image]

Interaction (Object Browser)
Send feedback

The Interaction module contains procedures used to interact with objects, applications, and systems. These constants can be used anywhere in your code.

To get Help on a particular procedure

  1. Select the procedure from the Members of 'Interaction' list.

  2. Click the [image] button.


Math (Object Browser)

 Copy code hover
[image]

Math (Object Browser)
Send feedback

The Math module contains procedures used to perform mathematical operations. These constants can be used anywhere in your code.

To get Help on a particular procedure

  1. Select the procedure from the Members of 'Math' list.

  2. Click the [image] button.


String (Object Browser)

 Copy code hover
[image]

String (Object Browser)
Send feedback

The Strings module contains procedures used to perform string operations. These constants can be used anywhere in your code.

To get Help on a particular procedure

  1. Select the procedure from the Members of 'Strings' list.

  2. Click the [image] button.


VbAppWinStyle (Object Browser)

 Copy code hover
[image]

VbAppWinStyle (Object Browser)
Send feedback

The VbAppWinStyle enumeration contains constants used by the Shell function to control the style of an application window. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbAppWinStyle' list.

  2. Click the [image] button.


VbCalendar (Object Browser)

 Copy code hover
[image]

VbCalendar (Object Browser)
Send feedback

The VbCalendar enumeration contains constants used to determine the type of calendar used by Visual Basic. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbCalendar' list.

  2. Click the [image] button.


VbCallType (Object Browser)

 Copy code hover
[image]

VbCallType (Object Browser)
Send feedback

The VbCallType enumeration defines constants used to identify the call type used by the CallByName function.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbCallType' list.

  2. Click the [image] button.


VbCompareMethod (Object Browser)

 Copy code hover
[image]

VbCompareMethod (Object Browser)
Send feedback

The VbCompareMethod enumeration contains constants used to determine the way strings are compared when using the Instr and StrComp functions. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbCompareMethod' list.

  2. Click the [image] button.


VbDateTimeFormat (Object Browser)

 Copy code hover
[image]

VbDateTimeFormat (Object Browser)
Send feedback

The VbDateTimeFormat enumeration defines constants used to identify how the date and time are formatted.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbDateTimeFormat' list.

  2. Click the [image] button.


VbDayOfWeek (Object Browser)

 Copy code hover
[image]

VbDayOfWeek (Object Browser)
Send feedback

The VbDayOfWeek enumeration contains constants used to identify specific days of the week when using the DateDiff, DatePart, and Weekday functions. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbDayOfWeek' list.

  2. Click the [image] button.


VbFileAttribute (Object Browser)

 Copy code hover
[image]

VbFileAttribute (Object Browser)
Send feedback

The VbFileAttribute enumeration contains constants used to identify file attributes used in the Dir, GetAttr, and SetAttr functions. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbFileAttribute' list.

  2. Click the [image] button.


VbFirstWeekOfYear (Object Browser)

 Copy code hover
[image]

VbFirstWeekOfYear (Object Browser)
Send feedback

The VbFirstWeekOfYear enumeration contains constants used to identify how the first week of a year is determined when using the DateDiff and DatePart functions. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbFirstWeekOfYear' list.

  2. Click the [image] button.


VbIMEStatus (Object Browser)

 Copy code hover
[image]

VbIMEStatus (Object Browser)
Send feedback

Available only in East Asia versions, the VbIMEStatus enumeration contains constants used to identify the Input Method Editor (IME) when using the IMEStatus function. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbIMEStatus' list.

  2. Click the [image] button.


VbMsgBoxResult (Object Browser)

 Copy code hover
[image]

VbMsgBoxResult (Object Browser)
Send feedback

The VbMsgBoxResult enumeration contains constants used to identify which button was pressed on a message box displayed using the MsgBox function. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbMsgBoxResult' list.

  2. Click the [image] button.


VbMsgBoxStyle (Object Browser)

 Copy code hover
[image]

VbMsgBoxStyle (Object Browser)
Send feedback

The VbMsgBoxStyle enumeration contains constants used to specify the behavior of a message box, along with symbols and buttons that appear on it, when displayed using the MsgBox function. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbMsgBoxStyle' list.

  2. Click the [image] button.


VbQueryClose (Object Browser)

 Copy code hover
[image]

VbQueryClose (Object Browser)
Send feedback

The VbQueryClose enumeration contains constants used to identify what caused the QueryClose event to occur. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbQueryClose' list.

  2. Click the [image] button.


VbStrConv (Object Browser)

 Copy code hover
[image]

VbStrConv (Object Browser)
Send feedback

The VbStrConv enumeration contains constants used to identify the type of string conversion to be performed by the StrConv function. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbStrConv' list.

  2. Click the [image] button.


VbTriState (Object Browser)

 Copy code hover
[image]

VbTriState (Object Browser)
Send feedback

The VbTriState enumeration defines constants used to identify one of three possible states.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbTriState' list.

  2. Click the [image] button.


VbVarType (Object Browser)

 Copy code hover
[image]

VbVarType (Object Browser)
Send feedback

The VbVarType enumeration contains constants used to identify the various types of data that can be contained in a Variant. These constants match the return values of the VarType function and can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'VbVarType' list.

  2. Click the [image] button.


Objects (Visual Basic for Applications)

 Copy code hover
[image]

Objects (Visual Basic for Applications)
Send feedback

In this section

  • Collection Object

  • Debug Object

  • Dictionary Object

  • Drive Object

  • Drives Collection

  • Err Object

  • File Object

  • Files Collection

  • FileSystemObject Object

  • Folder Object

  • Folders Collection

  • TextStream Object

  • UserForm Object


Collection Object

 Copy code hover
[image]

Collection Object
Send feedback

A Collection object is an ordered set of items that can be referred to as a unit.

Remarks

The Collection object provides a convenient way to refer to a related group of items as a single object. The items, or members, in a collection need only be related by the fact that they exist in the collection. Members of a collection don't have to share the same data type.

A collection can be created the same way other objects are created. For example:

Copy code Copy code
Dim X As New Collection

Once a collection is created, members can be added using the Add method and removed using the Remove method. Specific members can be returned from the collection using the Item method, while the entire collection can be iterated using the For Each...Next statement.

Example

This example creates a Collection object (MyClasses ), and then creates a dialog box in which users can add objects to the collection. To see how this works, choose the Class Module command from the Insert menu and declare a public variable called InstanceName at module level of Class1 (type Public InstanceName) to hold the names of each instance. Leave the default name as Class1. Copy and paste the following code into the General section of another module, and then start it with the statement ), ClassNamerand then creates a dialog box in which users can add objects to the collection. To see how this works, choose the Class Module command from the Insert menu and declare a public variable called InstanceName at module level of Class1 (type Public InstanceName) to hold the names of each instance. Leave the default name as Class1. Copy and paste the following code into the General section of another module, and then start it with the statement ClassNamer in another procedure. (This example only works with host applications that support classes.)

Copy code Copy code
Sub ClassNamer()
    Dim MyClasses As New Collection    ' Create a Collection object.
    Dim Num    ' Counter for individualizing keys.
    Dim Msg As String    ' Variable to hold prompt string.
    Dim TheName, MyObject, NameList    ' Variants to hold information.
    Do
        Dim Inst As New Class1    ' Create a new instance of Class1.
        Num = Num + 1    ' Increment Num, then get a name.
        Msg = "Please enter a name for this object." & Chr(13) _
         & "Press Cancel to see names in collection."
        TheName = InputBox(Msg, "Name the Collection Items")
        Inst.InstanceName = TheName    ' Put name in object instance.
        ' If user entered name, add it to the collection.
        If Inst.InstanceName <> "" Then
            ' Add the named object to the collection.
            MyClasses.Add item := Inst, key := CStr(Num)
        End If
        ' Clear the current reference in preparation for next one.
        Set Inst = Nothing
    Loop Until TheName = ""
    For Each MyObject In MyClasses    ' Create list of names.
        NameList = NameList & MyObject.InstanceName & Chr(13)
    Next MyObject
    ' Display the list of names in a message box.
    MsgBox NameList, , "Instance Names In MyClasses Collection"

    For Num = 1 To MyClasses.Count    ' Remove name from the collection.
        MyClasses.Remove 1    ' Since collections are reindexed
                ' automatically, remove the first
    Next        ' member on each iteration.
End Sub


Debug Object

 Copy code hover
[image]

Debug Object
Send feedback

The Debug object sends output to the Immediate window at run time.


Dictionary Object

 Copy code hover
[image]

Dictionary Object
Send feedback

Description

Object that stores data key, item pairs.

Syntax

Scripting.Dictionary

Remarks

A Dictionary object is the equivalent of a PERL associative array. Items, which can be any form of data, are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually a integer or a string, but can be anything except an array.

The following code illustrates how to create a Dictionary object:

Copy code Copy code
Dim d                   'Create a variable
Set d = CreateObject(Scripting.Dictionary)
d.Add "a", "Athens"     'Add some keys and items
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...


Drive Object

 Copy code hover
[image]

Drive Object
Send feedback

Description

Provides access to the properties of a particular disk drive or network share.

Remarks

The following code illustrates the use of the Drive object to access drive properties:

Copy code Copy code
Sub ShowFreeSpace(drvPath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(drvPath))
    s = "Drive " & UCase(drvPath) & " - "
    s = s & d.VolumeName  & vbCrLf
    s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
    s = s & " Kbytes"
    MsgBox s
End Sub


Drives Collection

 Copy code hover
[image]

Drives Collection
Send feedback

Description

Read-only collection of all available drives.

Remarks

Removable-media drives need not have media inserted for them to appear in the Drives collection.

The following code illustrates how to get the Drives collection and iterate the collection using the For Each...Next statement:

Copy code Copy code
Sub ShowDriveList
    Dim fs, d, dc, s, n
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set dc = fs.Drives
    For Each d in dc
        s = s & d.DriveLetter & " - "
        If d.DriveType = Remote Then
            n = d.ShareName
        Else
            n = d.VolumeName
        End If
        s = s & n & vbCrLf
    Next
    MsgBox s
End Sub


Err Object

 Copy code hover
[image]

Err Object
Send feedback

Contains information about run-time errors.

Remarks

The properties of the Err object are set by the generator of an error — Visual Basic, an object, or the programmer.

The default property of the Err object is Number. Because the default property can be represented by the object name Err, earlier code written using the Err function or Err statement doesn't have to be modified.

When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method.

The Err object's properties are reset to zero or zero-length strings ("") after an Exit Sub, Exit Function, Exit Property or Resume Next statement within an error-handling routine. Using any form of the Resume statement outside of an error-handling routine will not reset the Err object's properties. The Clear method can be used to explicitly reset Err.

Use the Raise method, rather than the Error statement, to generate run-time errors for system errors and class modules. Using the Raise method in other code depends on the richness of the information you want to return.

The Err object is an intrinsic object with global scope. There is no need to create an instance of it in your code.

Example

This example uses the properties of the Err object in constructing an error-message dialog box. Note that if you use the Clear method first, when you generate a Visual Basic error with the Raise method, Visual Basic's default values become the properties of the Err object.

Copy code Copy code
Dim Msg
' If an error occurs, construct an error message
On Error Resume Next    ' Defer error handling.
Err.Clear
Err.Raise 6    ' Generate an "Overflow" error.
' Check for error, then show message.
If Err.Number <> 0 Then
    Msg = "Error # " & Str(Err.Number) & " was generated by " _
            & Err.Source & Chr(13) & Err.Description
    MsgBox Msg, , "Error", Err.Helpfile, Err.HelpContext
End If


File Object

 Copy code hover
[image]

File Object
Send feedback

Description

Provides access to all the properties of a file.

Remarks

The following code illustrates how to obtain a File object and how to view one of its properties.

Copy code Copy code
Sub ShowFileInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = f.DateCreated
    MsgBox s
End Sub


Files Collection

 Copy code hover
[image]

Files Collection
Send feedback

Description

Collection of all File objects within a folder.

Remarks

The following code illustrates how to get a Files collection and iterate the collection using the For Each...Next statement:

Copy code Copy code
Sub ShowFolderList(folderspec)
    Dim fs, f, f1, fc, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set fc = f.Files
    For Each f1 in fc
        s = s & f1.name
        s = s & vbCrLf
    Next
    MsgBox s
End Sub


FileSystemObject Object

 Copy code hover
[image]

FileSystemObject Object
Send feedback

Description

Provides access to a computer's file system.

Syntax

Scripting.FileSystemObject

Remarks

The following code illustrates how the FileSystemObject is used to return a TextStream object that can be read from or written to:

VBA Copy code Copy code
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("c:\testfile.txt", True)
a.WriteLine("This is a test.")
a.Close

In the code shown above, the CreateObject function returns the FileSystemObject (fs ). The CreateTextFile method then creates the file as a TextStream object (a ), and the WriteLine method writes a line of text to the created text file. The Close method flushes the buffer and closes the file.


Folder Object

 Copy code hover
[image]

Folder Object
Send feedback

Description

Provides access to all the properties of a folder.

Remarks

The following code illustrates how to obtain a Folder object and how to return one of its properties:

Copy code Copy code
Sub ShowFolderInfo(folderspec)
    Dim fs, f, s,
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    s = f.DateCreated
    MsgBox s
End Sub


Folders Collection

 Copy code hover
[image]

Folders Collection
Send feedback

Description

Collection of all Folder objects contained within a Folder object.

Remarks

The following code illustrates how to get a Folders collection and how to iterate the collection using the For Each...Next statement:

Copy code Copy code
Sub ShowFolderList(folderspec)
    Dim fs, f, f1, fc, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set fc = f.SubFolders
    For Each f1 in fc
        s = s & f1.name
        s = s &  vbCrLf
    Next
    MsgBox s
End Sub


TextStream Object

 Copy code hover
[image]

TextStream Object
Send feedback

Description

Facilitates sequential access to file.

Syntax

TextStream.{property | method}

The property and method arguments can be any of the properties and methods associated with the TextStream object. Note that in actual usage TextStream is replaced by a variable placeholder representing the TextStream object returned from the FileSystemObject.

Remarks

In the following code, a is the TextStream object returned by the CreateTextFile method on the FileSystemObject:

WriteLine and Close are two methods of the TextStream Object.

Copy code Copy code
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("c:\testfile.txt", True)
a.WriteLine("This is a test.")
a.Close


UserForm Object

 Copy code hover
[image]

UserForm Object
Send feedback

A UserForm object is a window or dialog box that makes up part of an application's user interface.

The UserForms collection is a collection whose elements represent each loaded UserForm in an application. The UserForms collection has a Count property, an Item property, and an Add method. Count specifies the number of elements in the collection; Item (the default member) specifies a specific collection member; and Add places a new UserForm element in the collection.

Syntax

UserForm

UserForms[.Item](index)

The placeholder index represents an integer with a range from 0 to UserForms.Count - 1. Item is the default member of the UserForms collection and need not be specified.

Remarks

You can use the UserForms collection to iterate through all loaded user forms in an application. It identifies an intrinsic global variable named UserForms. You can pass UserForms(index) to a function whose argument is specified as a UserForm class.

User forms have properties that determine appearance such as position, size, and color; and aspects of their behavior.

User forms can also respond to events initiated by a user or triggered by the system. For example, you can write code in the Initialize event procedure of the UserForm to initialize module-level variables before the UserForm is displayed.

In addition to properties and events, you can use methods to manipulate user forms using code. For example, you can use the Move method to change the location and size of a UserForm.

When designing user forms, set the BorderStyle property to define borders, and set the Caption property to put text in the title bar. In code, you can use the Hide and Show methods to make a UserForm invisible or visible at run time.

UserForm is an Object data type. You can declare variables as type UserForm before setting them to an instance of a type of UserForm declared at design time. Similarly, you can pass an argument to a procedure as type UserForm. You can create multiple instances of user forms in code by using the New keyword in Dim, Set, and Static statements.

You can access the collection of controls on a UserForm using the Controls collection. For example, to hide all the controls on a UserForm, use code similar to the following:

Copy code Copy code
For Each Control in UserForm1.Controls
    Control.Visible = False
Next Control


Operators

 Copy code hover
[image]

Operators
Send feedback

In this section

  • Operator Summary

  • Operator Precedence

  • - Operator

  • & Operator

  • * Operator

  • / Operator

  • \ Operator

  • ^ Operator

  • + Operator

  • = Operator

  • AddressOf Operator

  • And Operator

  • Arithmetic Operators

  • Comparison Operators

  • Concatenation Operators

  • Eqv Operator

  • Imp Operator

  • Is Operator

  • Like Operator

  • Logical Operators

  • Mod Operator

  • Not Operator

  • Or Operator

  • Xor Operator


Operator Summary

 Copy code hover
[image]

Operator Summary
Send feedback

Operators | Description
Arithmetic Operators | Operators used to perform mathematical calculations.
Comparison Operators | Operators used to perform comparisons.
Concatenation Operators | Operators used to combine strings.
Logical Operators | Operators used to perform logical operations.


Operator Precedence

 Copy code hover
[image]

Operator Precedence
Send feedback

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence:

Arithmetic | Comparison | Logical
Exponentiation (^) | Equality (=) | Not
Negation (-) | Inequality (<>) | And
Multiplication and division (*, /) | Less than (<) | Or
Integer division (\) | Greater than (>) | Xor
Modulus arithmetic (Mod) | Less than or equal to (<=) | Eqv
Addition and subtraction (+, -) | Greater than or equal to (>=) | Imp
String concatenation (&) | Like Is |

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. When addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right. Parentheses can be used to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, operator precedence is maintained.

The string concatenation operator (&) is not an arithmetic operator, but in precedence, it does follow all arithmetic operators and precede all comparison operators.

The Like operator is equal in precedence to all comparison operators, but is actually a pattern-matching operator.

The Is operator is an object reference comparison operator. It does not compare objects or their values; it checks only to determine if two object references refer to the same object.


- Operator

 Copy code hover
[image]

- Operator
Send feedback

Used to find the difference between two numbers or to indicate the negative value of a numeric expression.

Syntax 1

result = number1-number2

Syntax 2

- number

The - operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
number | Required; any numeric expression.
number1 | Required; any numeric expression.
number2 | Required; any numeric expression.

Remarks

In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between two numbers. In Syntax 2, the - operator is used as the unary negation operator to indicate the negative value of an expression.

The data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Integer, Long, Single, Double, Currency, and Decimal. The following are exceptions to this order:

If | Then result is
Subtraction involves a Single and a Long, | converted to a Double.
The data type of result is a Long, Single, or Date variant that overflows its legal range, | converted to a iVariant containing a Double.
The data type of result is a Byte variant that overflows its legal range, | converted to an Integer variant.
The data type of result is an Integer variant that overflows its legal range, | converted to a Long variant.
Subtraction involves a Date and any other data type, | a Date.
Subtraction involves two Date expressions, | a Double.

One or both expressions are Null expressions, result is Null. If an expression is Empty, it is treated as 0.

Note Note

The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication.

Example

This example uses the - operator to calculate the difference between two numbers.

Copy code Copy code
Dim MyResult
MyResult = 4 - 2    ' Returns 2.
MyResult = 459.35 - 334.90    ' Returns 124.45.


& Operator

 Copy code hover
[image]

& Operator
Send feedback

Used to force string concatenation of two expressions.

Syntax

result = expression1 & expression2

The & operator syntax has these parts:

Part | Description
result | Required; any String or Variant variable.
expression1 | Required; any expression.
expression2 | Required; any expression.

Remarks

If an expression is not a string, it is converted to a String variant. The data type of result is String if both expressions are string expressions; otherwise, result is a String variant. If both expressions are Null, result is Null. However, if only one expression is Null, that expression is treated as a zero-length string ("") when concatenated with the other expression. Any expression that is Empty is also treated as a zero-length string.

Example

This example uses the & operator to force string concatenation.

Copy code Copy code
Dim MyStr
MyStr = "Hello" & " World"    ' Returns "Hello World".
MyStr = "Check " & 123 & " Check"    ' Returns "Check 123 Check".


* Operator

 Copy code hover
[image]

* Operator
Send feedback

Used to multiply two numbers.

Syntax

result = number1*number2

The * operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
number1 | Required; any numeric expression.
number2 | Required; any numeric expression.

Remarks

The data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Integer, Long, Single, Currency, Double, and Decimal. The following are exceptions to this order:

If | Then result is
Multiplication involves a Single and a Long, | converted to a Double.
The data type of result is a Long, Single, or Date variant that overflows its legal range, | converted to a Variant containing a Double.
The data type of result is a Byte variant that overflows its legal range, | converted to an Integer variant.
the data type of result is an Integer variant that overflows its legal range, | converted to a Long variant.

If one or both expressions are Null expressions, result is Null. If an expression is Empty, it is treated as 0.

Note Note

The order of precision used by multiplication is not the same as the order of precision used by addition and subtraction.

Example

This example uses the * operator to multiply two numbers.

Copy code Copy code
Dim MyValue
MyValue = 2 * 2    ' Returns 4.
MyValue = 459.35 * 334.90     ' Returns 153836.315.


/ Operator

 Copy code hover
[image]

/ Operator
Send feedback

Used to divide two numbers and return a floating-point result.

Syntax

result = number1 / number2

The / operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
number1 | Required; any numeric expression.
number2 | Required; any numeric expression.

Remarks

The data type of result is usually a Double or a Double variant. The following are exceptions to this rule:

If | Then result is
Both expressions are Byte, Integer, or Single expressions, | a Single unless it overflows its legal range; in which case, an error occurs.
Both expressions are Byte, Integer, or Single variants, | a Single variant unless it overflows its legal range; in which case, result is a Variant containing a Double.
Division involves a Decimal and any other data type, | a Decimal data type.

One or both expressions are Null expressions, result is Null. Any expression that is Empty is treated as 0.

Example

This example uses the / operator to perform floating-point division.

Copy code Copy code
Dim MyValue
MyValue = 10 / 4    ' Returns 2.5.
MyValue = 10 / 3    ' Returns 3.333333.


\ Operator

 Copy code hover
[image]

\ Operator
Send feedback

Used to divide two numbers and return an integer result.

Syntax

result = number1 \ number2

The \ operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
number1 | Required; any numeric expression.
number2 | Required; any numeric expression.

Remarks

Before division is performed, the numeric expressions are rounded to Byte, Integer, or Long expressions.

Usually, the data type of result is a Byte, Byte variant, Integer, Integer variant, Long, or Long variant, regardless of whether result is a whole number. Any fractional portion is truncated. However, if any expression is Null, result is Null. Any expression that is Empty is treated as 0.

Example

This example uses the \ operator to perform integer division.

Copy code Copy code
Dim MyValue
MyValue = 11 \ 4    ' Returns 2.
MyValue = 9 \ 3    ' Returns 3.
MyValue = 100 \ 3    ' Returns 33.


^ Operator

 Copy code hover
[image]

^ Operator
Send feedback

Used to raise a number to the power of an exponent.

Syntax

result = number ^ exponent

The ^ operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
number | Required; any numeric expression.
exponent | Required; any numeric expression.

Remarks

A number can be negative only if exponent is an integer value. When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from left to right.

Usually, the data type of result is a Double or a Variant containing a Double. However, if either number or exponent is a Null expression, result is Null.

Example

This example uses the ^ operator to raise a number to the power of an exponent.

Copy code Copy code
Dim MyValue
MyValue = 2 ^ 2    ' Returns 4.
MyValue = 3 ^ 3 ^ 3    ' Returns 19683.
MyValue = (-5) ^ 3    ' Returns -125.


+ Operator

 Copy code hover
[image]

+ Operator
Send feedback

Used to sum two numbers.

Syntax

result = expression1+expression2

The + operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
expression1 | Required; any expression.
expression2 | Required; any expression.

Remarks

When you use the + operator, you may not be able to determine whether addition or string concatenation will occur. Use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.

If at least one expression is not a Variant, the following rules apply:

If | Then
Both expressions are numeric data types (Byte, Boolean, Integer, Long, Single, Double, Date, Currency, or Decimal) | Add.
Both expressions are String | Concatenate.
One expression is a numeric data type and the other is any Variant except Null | Add.
One expression is a String and the other is any Variant except Null | Concatenate.
One expression is an Empty Variant | Return the remaining expression unchanged as result.
One expression is a numeric data type and the other is a String | A Type mismatch error occurs.
Either expression is Null | result is Null.

If both expressions are Variant expressions, the following rules apply:

If | Then
Both Variant expressions are numeric | Add.
Both Variant expressions are strings | Concatenate.
One Variant expression is numeric and the other is a string | Add.

For simple arithmetic addition involving only expressions of numeric data types, the data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Integer, Long, Single, Double, Currency, and Decimal. The following are exceptions to this order:

If | Then result is
A Single and a Long are added, | a Double.
The data type of result is a Long, Single, or Date variant that overflows its legal range, | converted to a Double variant.
The data type of result is a Byte variant that overflows its legal range, | converted to an Integer variant.
The data type of result is an Integer variant that overflows its legal range, | converted to a Long variant.
A Date is added to any data type, | a Date.

If one or both expressions are Null expressions, result is Null. If both expressions are Empty, result is an Integer. However, if only one expression is Empty, the other expression is returned unchanged as result.

Note Note

The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication.

Example

This example uses the + operator to sum numbers. The + operator can also be used to concatenate strings. However, to eliminate ambiguity, you should use the & operator instead. If the components of an expression created with the + operator include both strings and numerics, the arithmetic result is assigned. If the components are exclusively strings, the strings are concatenated.

Copy code Copy code
Dim MyNumber, Var1, Var2
MyNumber = 2 + 2    ' Returns 4.
MyNumber = 4257.04 + 98112    ' Returns 102369.04.

Var1 = "34": Var2 = 6    ' Initialize mixed variables.
MyNumber = Var1 + Var2    ' Returns 40.

Var1 = "34": Var2 = "6"    ' Initialize variables with strings.
MyNumber = Var1 + Var2    ' Returns "346" (string concatenation).


= Operator

 Copy code hover
[image]

= Operator
Send feedback

Description

Used to assign a value to a variable or property.

Syntax

variable = value

The = operator syntax has these parts:

Part | Description
variable | Any variable or any writable property.
value | Any numeric or string literal, constant, or expression.

Remarks

The name on the left side of the equal sign can be a simple scalar variable or an element of an array. Properties on the left side of the equal sign can only be those properties that are writable at run time.


AddressOf Operator

 Copy code hover
[image]

AddressOf Operator
Send feedback

A unary operator that causes the address of the procedure it precedes to be passed to an API procedure that expects a function pointer at that position in the argument list.

Syntax

AddressOf procedurename

The required procedurename specifies the procedure whose address is to be passed. It must represent a procedure in a standard module module in the project in which the call is made.

Remarks

When a procedure name appears in an argument list, usually the procedure is evaluated, and the address of the procedure's return value is passed. AddressOf permits the address of the procedure to be passed to a Windows API function in a dynamic-link library (DLL), rather passing the procedure's return value. The API function can then use the address to call the Basic procedure, a process known as a callback. The AddressOf operator appears only in the call to the API procedure.

Although you can use AddressOf to pass procedure pointers among Basic procedures, you can't call a function through such a pointer from within Basic. This means, for example, that a class written in Basic can't make a callback to its controller using such a pointer. When using AddressOf to pass a procedure pointer among procedures within Basic, the parameter of the called procedure must be typed As Long.

Using AddressOf may cause unpredictable results if you don't completely understand the concept of function callbacks. You must understand how the Basic portion of the callback works, and also the code of the DLL into which you are passing your function address. Debugging such interactions is difficult since the program runs in the same process as the development environment. In some cases, systematic debugging may not be possible.

Note Note

You can create your own call-back function prototypes in DLLs compiled with Microsoft Visual C++ (or similar tools). To work with AddressOf, your prototype must use the __stdcall calling convention. The default calling convention (__cdecl) will not work with AddressOf.

Since the caller of a callback is not within your program, it is important that an error in the callback procedure not be propagated back to the caller. You can accomplish this by placing the On Error Resume Next statement at the beginning of the callback procedure.

Example

The following example creates a form with a list box containing an alphabetically sorted list of the fonts in your system.

To run this example, create a form with a list box on it. The code for the form is as follows:

Copy code Copy code
Option Explicit

Private Sub Form_Load()
    Module1.FillListWithFonts List1
End Sub

Place the following code in a module. The third argument in the definition of the EnumFontFamilies function is a Long that represents a procedure. The argument must contain the address of the procedure, rather than the value that the procedure returns. In the call to EnumFontFamilies, the third argument requires the AddressOf operator to return the address of the EnumFontFamProc procedure, which is the name of the callback procedure you supply when calling the Windows API function, EnumFontFamilies. Windows calls EnumFontFamProc once for each of the font families on the system when you pass AddressOf EnumFontFamProc to EnumFontFamilies. The last argument passed to EnumFontFamilies specifies the list box in which the information is displayed.

Copy code Copy code
'Font enumeration types
Public Const LF_FACESIZE = 32
Public Const LF_FULLFACESIZE = 64

Type LOGFONT
        lfHeight As Long
        lfWidth As Long
        lfEscapement As Long
        lfOrientation As Long
        lfWeight As Long
        lfItalic As Byte
        lfUnderline As Byte
        lfStrikeOut As Byte
        lfCharSet As Byte
        lfOutPrecision As Byte
        lfClipPrecision As Byte
        lfQuality As Byte
        lfPitchAndFamily As Byte
        lfFaceName(LF_FACESIZE) As Byte
End Type

Type NEWTEXTMETRIC
        tmHeight As Long
        tmAscent As Long
        tmDescent As Long
        tmInternalLeading As Long
        tmExternalLeading As Long
        tmAveCharWidth As Long
        tmMaxCharWidth As Long
        tmWeight As Long
        tmOverhang As Long
        tmDigitizedAspectX As Long
        tmDigitizedAspectY As Long
        tmFirstChar As Byte
        tmLastChar As Byte
        tmDefaultChar As Byte
        tmBreakChar As Byte
        tmItalic As Byte
        tmUnderlined As Byte
        tmStruckOut As Byte
        tmPitchAndFamily As Byte
        tmCharSet As Byte
        ntmFlags As Long
        ntmSizeEM As Long
        ntmCellHeight As Long
        ntmAveWidth As Long
End Type

' ntmFlags field flags
Public Const NTM_REGULAR = &H40&
Public Const NTM_BOLD = &H20&
Public Const NTM_ITALIC = &H1&

'  tmPitchAndFamily flags
Public Const TMPF_FIXED_PITCH = &H1
Public Const TMPF_VECTOR = &H2
Public Const TMPF_DEVICE = &H8
Public Const TMPF_TRUETYPE = &H4

Public Const ELF_VERSION = 0
Public Const ELF_CULTURE_LATIN = 0

'  EnumFonts Masks
Public Const RASTER_FONTTYPE = &H1
Public Const DEVICE_FONTTYPE = &H2
Public Const TRUETYPE_FONTTYPE = &H4

Declare Function EnumFontFamilies Lib "gdi32" Alias _
     "EnumFontFamiliesA" _
     (ByVal hDC As Long, ByVal lpszFamily As String, _
     ByVal lpEnumFontFamProc As Long, LParam As Any) As Long
Declare Function GetDC Lib "user32" (ByVal hWnd As Long) As Long
Declare Function ReleaseDC Lib "user32" (ByVal hWnd As Long, _
     ByVal hDC As Long) As Long

Function EnumFontFamProc(lpNLF As LOGFONT, lpNTM As NEWTEXTMETRIC, _
     ByVal FontType As Long, LParam As ListBox) As Long
Dim FaceName As String
Dim FullName As String
    FaceName = StrConv(lpNLF.lfFaceName, vbUnicode)
    LParam.AddItem Left$(FaceName, InStr(FaceName, vbNullChar) - 1)
    EnumFontFamProc = 1
End Function

Sub FillListWithFonts(LB As ListBox)
Dim hDC As Long
    LB.Clear
    hDC = GetDC(LB.hWnd)
    EnumFontFamilies hDC, vbNullString, AddressOf EnumFontFamProc, LB
    ReleaseDC LB.hWnd, hDC
End Sub


And Operator

 Copy code hover
[image]

And Operator
Send feedback

Used to perform a logical conjunction on two expressions.

Syntax

result = expression1 And expression2

The And operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
expression1 | Required; any expression.
expression2 | Required; any expression.

Remarks

If both expressions evaluate to True, result is True. If either expression evaluates to False, result is False. The following table illustrates how result is determined:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | False
True | Null | Null
False | True | False
False | False | False
False | Null | False
Null | True | Null
Null | False | False
Null | Null | Null

The And operator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

Example

This example uses the And operator to perform a logical conjunction on two expressions.

Copy code Copy code
Dim A, B, C, D, MyCheck
A = 10: B = 8: C = 6: D = Null    ' Initialize variables.
MyCheck = A > B And B > C    ' Returns True.
MyCheck = B > A And B > C    ' Returns False.
MyCheck = A > B And B > D    ' Returns Null.
MyCheck = A And B    ' Returns 8 (bitwise comparison).


Arithmetic Operators

 Copy code hover
[image]

Arithmetic Operators
Send feedback

^ Operator

* Operator

/ Operator

\ Operator

Mod Operator

+ Operator

- Operator


Comparison Operators

 Copy code hover
[image]

Comparison Operators
Send feedback

Used to compare expressions.

Syntax

result = expression1 comparisonoperator expression2

result = object1 Is object2

result = string Like pattern

Comparison operators have these parts:

Part | Description
result | Required; any numeric variable.
expression | Required; any expression.
comparisonoperator | Required; any comparison operator.
object | Required; any object name.
string | Required; any string expression.
pattern | Required; any string expression or range of characters.

Remarks

The following table contains a list of the comparison operators and the conditions that determine whether result is True, False, or Null:

Operator | True if | False if | Null if
< (Less than) | expression1 < expression2 | expression1 >= expression2 | expression1 or expression2 = Null
<= (Less than or equal to) | expression1 <= expression2 | expression1 > expression2 | expression1 or expression2 = Null
> (Greater than) | expression1 > expression2 | expression1 <= expression2 | expression1 or expression2 = Null
>= (Greater than or equal to) | expression1 >= expression2 | expression1 < expression2 | expression1 or expression2 = Null
= (Equal to) | expression1 = expression2 | expression1 <> expression2 | expression1 or expression2 = Null
<> (Not equal to) | expression1 <> expression2 | expression1 = expression2 | expression1 or expression2 = Null
Note Note

The Is and Like operators have specific comparison functionality that differs from the operators in the table.

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 the result when either expression is not a Variant:

If | Then
Both expressions are numeric data types (Byte, Boolean, Integer, Long, Single, Double, Date, Currency, or Decimal) | Perform a numeric comparison.
Both expressions are String | Perform a string comparison.
One expression is a numeric data type and the other is a Variant that is, or can be, a number | Perform a numeric comparison.
One expression is a numeric data type and the other is a string Variant that can't be converted to a number | A Type Mismatch error occurs.
One expression is a String and the other is any Variant except a Null | Perform a string comparison.
One expression is Empty and the other is a numeric data type | Perform a numeric comparison, using 0 as the Empty expression.
One expression is Empty and the other is a String | Perform a string comparison, using a zero-length string ("") as the Empty expression.

If expression1 and expression2 are both Variant expressions, their underlying type determines how they are compared. The following table shows how the expressions are compared or the result from the comparison, depending on the underlying type of the Variant:

If | Then
Both Variant expressions are numeric | Perform a numeric comparison.
Both Variant expressions are strings | Perform a string comparison.
One Variant expression is numeric and the other is a string | The numeric expression is less than the string expression.
One Variant expression is Empty and the other is numeric | Perform a numeric comparison, using 0 as the Empty expression.
One Variant expression is Empty and the other is a string | Perform a string comparison, using a zero-length string ("") as the Empty expression.
Both Variant expressions are Empty | The expressions are equal.

When a Single is compared to a Double, the Double is rounded to the precision of the Single.

If a Currency is compared with a Single or Double, the Single or Double is converted to a Currency. Similarly, when a Decimal is compared with a Single or Double, the Single or Double is converted to a Decimal. For Currency, any fractional value less than .0001 may be lost; for Decimal, any fractional value less than 1E-28 may be lost, or an overflow error can occur. Such fractional value loss may cause two values to compare as equal when they are not.

Example

This example shows various uses of comparison operators, which you use to compare expressions.

Copy code Copy code
Dim MyResult, Var1, Var2
MyResult = (45 < 35)    ' Returns False.
MyResult = (45 = 45)    ' Returns True.
MyResult = (4 <> 3)    ' Returns True.
MyResult = ("5" > "4")    ' Returns True.

Var1 = "5": Var2 = 4    ' Initialize variables.
MyResult = (Var1 > Var2)    ' Returns True.

Var1 = 5: Var2 = Empty
MyResult = (Var1 > Var2)    ' Returns True.

Var1 = 0: Var2 = Empty
MyResult = (Var1 = Var2)    ' Returns True.


Concatenation Operators

 Copy code hover
[image]

Concatenation Operators
Send feedback

& Operator

+ Operator


Eqv Operator

 Copy code hover
[image]

Eqv Operator
Send feedback

Used to perform a logical equivalence on two expressions.

Syntax

result = expression1 Eqv expression2

The Eqv operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
expression1 | Required; any expression.
expression2 | Required; any expression.

Remarks

If either expression is Null, result is also Null. When neither expression is Null, result is determined according to the following table:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | False
False | True | False
False | False | True

The Eqv operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 1
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

Example

This example uses the Eqv operator to perform logical equivalence on two expressions.

Copy code Copy code
Dim A, B, C, D, MyCheck
A = 10: B = 8: C = 6: D = Null    ' Initialize variables.
MyCheck = A > B Eqv B > C    ' Returns True.
MyCheck = B > A Eqv B > C    ' Returns False.
MyCheck = A > B Eqv B > D    ' Returns Null.
MyCheck = A Eqv B    ' Returns -3 (bitwise comparison).


Imp Operator

 Copy code hover
[image]

Imp Operator
Send feedback

Used to perform a logical implication on two expressions.

Syntax

result = expression1 Imp expression2

The Imp operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
expression1 | Required; any expression.
expression2 | Required; any expression.

Remarks

The following table illustrates how result is determined:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | False
True | Null | Null
False | True | True
False | False | True
False | Null | True
Null | True | True
Null | False | Null
Null | Null | Null

The Imp operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 1
0 | 1 | 1
1 | 0 | 0
1 | 1 | 1

Example

This example uses the Imp operator to perform logical implication on two expressions.

Copy code Copy code
Dim A, B, C, D, MyCheck
A = 10: B = 8: C = 6: D = Null    ' Initialize variables.
MyCheck = A > B Imp B > C    ' Returns True.
MyCheck = A > B Imp C > B    ' Returns False.
MyCheck = B > A Imp C > B    ' Returns True.
MyCheck = B > A Imp C > D    ' Returns True.
MyCheck = C > D Imp B > A    ' Returns Null.
MyCheck = B Imp A    ' Returns -1 (bitwise comparison).


Is Operator

 Copy code hover
[image]

Is Operator
Send feedback

Used to compare two object reference variables.

Syntax

result = object1 Is object2

The Is operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
object1 | Required; any object name.
object2 | Required; any object name.

Remarks

If object1 and object2 both refer to the same object, result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways.

In the following example, A has been set to refer to the same object as B:

Copy code Copy code
Set A = B

The following example makes A and B refer to the same object as C:

Copy code Copy code
Set A = C
Set B = C

Example

This example uses the Is operator to compare two object references. The object variable names are generic and used for illustration purposes only.

Copy code Copy code
Dim MyObject, YourObject, ThisObject, OtherObject, ThatObject, MyCheck
Set YourObject = MyObject    ' Assign object references.
Set ThisObject = MyObject
Set ThatObject = OtherObject
MyCheck = YourObject Is ThisObject    ' Returns True.
MyCheck = ThatObject Is ThisObject    ' Returns False.
' Assume MyObject <> OtherObject
MyCheck = MyObject Is ThatObject    ' Returns False.


Like Operator

 Copy code hover
[image]

Like Operator
Send feedback

Used to compare two strings.

Syntax

result = string Like pattern

The Like operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
string | Required; any string expression.
pattern | Required; any string expression conforming to the pattern-matching conventions described in Remarks.

Remarks

If string matches pattern, result is True; if there is no match, result is False. If either string or pattern is Null, result is Null.

The behavior of the Like operator depends on the Option Compare statement. The default string-comparison method for each module is Option Compare Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. Sort order is determined by the code page. In the following example, a typical binary sort order is shown:

A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive, textual sort order determined by your system's locale. When you sort the same characters using Option Compare Text, the following text sort order is produced:

(A=a) < (À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Characters in pattern | Matches in string
? | Any single character.
* | Zero or more characters.
# | Any single digit (0-9).
[charlist] | Any single character in charlist.
[!charlist] | Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note Note

To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

By using a hyphen (-) to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A-Z. Multiple ranges are included within the brackets without delimiters.

The meaning of a specified range depends on the character ordering valid at run time (as determined by Option Compare and the locale setting of the system the code is running on). Using the Option Compare Binary example, the range [A-E] matches A, B and E. With Option Compare Text, [A-E] matches A, a, À, à, B, b, E, e. The range does not match Ê or ê because accented characters fall after unaccented characters in the sort order.

Other important rules for pattern matching include the following:

  • An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself.

  • A hyphen (-) can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.

  • When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.

  • The character sequence [] is considered a zero-length string ("").

In some languages, there are special characters in the alphabet that represent two separate characters. For example, several languages use the character "æ" to represent the characters "a" and "e" when they appear together. The Like operator recognizes that the single special character and the two individual characters are equivalent.

When a language that uses a special character is specified in the system locale settings, an occurrence of the single special character in either pattern or string matches the equivalent 2-character sequence in the other string. Similarly, a single special character in pattern enclosed in brackets (by itself, in a list, or in a range) matches the equivalent 2-character sequence in string.

Example

This example uses the Like operator to compare a string to a pattern.

VBA Copy code Copy code
Dim MyCheck
MyCheck = "aBBBa" Like "a*a"    ' Returns True.
MyCheck = "F" Like "[A-Z]"    ' Returns True.
MyCheck = "F" Like "[!A-Z]"    ' Returns False.
MyCheck = "a2a" Like "a#a"    ' Returns True.
MyCheck = "aM5b" Like "a[L-P]#[!c-e]"    ' Returns True.
MyCheck = "BAT123khg" Like "B?T*"    ' Returns True.
MyCheck = "CAT123khg" Like "B?T*"    ' Returns False.


Logical Operators

 Copy code hover
[image]

Logical Operators
Send feedback

And Operator

Eqv Operator

Imp Operator

Not Operator

Or Operator

Xor Operator


Mod Operator

 Copy code hover
[image]

Mod Operator
Send feedback

Used to divide two numbers and return only the remainder.

Syntax

result = number1 Mod number2

The Mod operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
number1 | Required; any numeric expression.
number2 | Required; any numeric expression.

Remarks

The modulus, or remainder, operator divides number1 by number2 (rounding floating-point numbers to integers) and returns only the remainder as result. For example, in the following expression, A (result) equals 5.

Usually, the data type of result is a Byte, Byte variant, Integer, Integer variant, Long, or Variant containing a Long, regardless of whether or not result is a whole number. Any fractional portion is truncated. However, if any expression is Null, result is Null. Any expression that is Empty is treated as 0.

Example

This example uses the Mod operator to divide two numbers and return only the remainder. If either number is a floating-point number, it is first rounded to an integer.

Copy code Copy code
Dim MyResult
MyResult = 10 Mod 5    ' Returns 0.
MyResult = 10 Mod 3    ' Returns 1.
MyResult = 12 Mod 4.3    ' Returns 0.
MyResult = 12.6 Mod 5    ' Returns 3.


Not Operator

 Copy code hover
[image]

Not Operator
Send feedback

Used to perform logical negation on an expression.

Syntax

result = Not expression

The Not operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
expression | Required; any expression.

Remarks

The following table illustrates how result is determined:

If expression is | Then result is
True | False
False | True
Null | Null

In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit in result according to the following table:

If bit in expression is | Then bit in result is
o | 1
1 | 0

Example

This example uses the Not operator to perform logical negation on an expression.

Copy code Copy code
Dim A, B, C, D, MyCheck
A = 10: B = 8: C = 6: D = Null    ' Initialize variables.
MyCheck = Not(A > B)    ' Returns False.
MyCheck = Not(B > A)    ' Returns True.
MyCheck = Not(C > D)    ' Returns Null.
MyCheck = Not A    ' Returns -11 (bitwise comparison).


Or Operator

 Copy code hover
[image]

Or Operator
Send feedback

Used to perform a logical disjunction on two expressions.

Syntax

result = expression1 Or expression2

The Or operator syntax has these parts:

Part | Description
result | Required; any numeric variable.
expression1 | Required; any expression.
expression2 | Required; any expression.

Remarks

If either or both expressions evaluate to True, result is True. The following table illustrates how result is determined:

If expression1 is | And expression2 is | Then result is
True | True | True
True | False | True
True | Null | True
False | True | True
False | False | False
False | Null | Null
Null | True | True
Null | False | Null
Null | Null | Null

The Or operator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

If bit in expression1 is | And bit in expression2 is | Then result is
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 1

Example

This example uses the Or operator to perform logical disjunction on two expressions.

Copy code Copy code
Dim A, B, C, D, MyCheck
A = 10: B = 8: C = 6: D = Null    ' Initialize variables.
MyCheck = A > B Or B > C    ' Returns True.
MyCheck = B > A Or B > C    ' Returns True.
MyCheck = A > B Or B > D    ' Returns True.
MyCheck = B > D Or B > A    ' Returns Null.
MyCheck = A Or B    ' Returns 10 (bitwise comparison).


Xor Operator

 Copy code hover
[image]

Xor Operator
Send feedback

Used to perform a logical exclusion on two expressions.

Syntax

[result =] expression1 Xor expression2

The Xor operator syntax has these parts:

Part | Description
result | Optional; any numeric variable.
expression1 | Required; any expression.
expression2 | Required; any expression.

Remarks

If one, and only one, of the expressions evaluates to True, result is True. However, if either expression is Null, result is also Null. When neither expression is Null, result is determined according to the following table:

If expression1 is | And expression2 is | Then result is
True | True | False
True | False | True
False | True | True
False | False | False

The Xor operator performs as both a logical and bitwise operator. A bit-wise comparison of two expressions using exclusive-or logic to form the result, as shown in the following table:

If bit in expression1 is | And bit in expression2 is | Then result is
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0

Example

This example uses the Xor operator to perform logical exclusion on two expressions.

Copy code Copy code
Dim A, B, C, D, MyCheck
A = 10: B = 8: C = 6: D = Null    ' Initialize variables.
MyCheck = A > B Xor B > C    ' Returns False.
MyCheck = B > A Xor B > C    ' Returns True.
MyCheck = B > A Xor C > B    ' Returns False.
MyCheck = B > D Xor A > B    ' Returns Null.
MyCheck = A Xor B    ' Returns 2 (bitwise comparison).


Properties (Visual Basic for Applications)

 Copy code hover
[image]

Properties (Visual Basic for Applications)
Send feedback

In this section

  • AtEndOfLine Property

  • AtEndOfStream Property

  • Attributes Property

  • AvailableSpace Property

  • Calendar Property

  • Column Property (Visual Basic for Applications)

  • CompareMode Property

  • Count Property (FileSystemObject object)

  • Count Property (Visual Basic for Applications)

  • DateCreated Property

  • DateLastAccessed Property

  • DateLastModified Property

  • Description Property (Visual Basic for Applications)

  • Drive Property

  • DriveLetter Property

  • Drives Property

  • DriveType Property

  • Files Property

  • FileSystem Property

  • FreeSpace Property

  • HelpContext Property (Visual Basic for Applications)

  • HelpFile Property

  • IsReady Property

  • IsRootFolder Property

  • Item Property (FileSystemObject object)

  • Key Property

  • LastDLLError Property

  • Line Property

  • Name Property (FileSystemObject object)

  • Number Property (Visual Basic for Applications)

  • ParentFolder Property

  • Path Property (FileSystemObject object)

  • RightToLeft Property

  • RootFolder Property

  • SerialNumber Property

  • ShareName Property

  • ShortName Property

  • ShortPath Property

  • ShowModal Property

  • Size Property (FileSystemObject object)

  • Source Property (Visual Basic for Applications)

  • StartUpPosition Property

  • SubFolders Property

  • TotalSize Property

  • Type Property (FileSystemObject object)

  • VBComponents Property

  • VolumeName Property

  • WhatsThisButton Property

  • WhatsThisHelp Property


AtEndOfLine Property

 Copy code hover
[image]

AtEndOfLine Property
Send feedback

Description

Read-only property that returns True if the file pointer immediately precedes the end-of-line marker in a TextStream file; False if it does not.

Syntax

object.AtEndOfLine

The object is always the name of a TextStream object.

Remarks

The AtEndOfLine property applies only to TextStream files that are open for reading; otherwise, an error occurs.

The following code illustrates the use of the AtEndOfLine property:

Copy code Copy code
Dim fs, a, retstring
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile("c:\testfile.txt", ForReading, False)
Do While a. AtEndOfLine <> True
    retstring = a.Read(1)
    ...
Loop
a.Close


AtEndOfStream Property

 Copy code hover
[image]

AtEndOfStream Property
Send feedback

Description

Read-only property that returns True if the file pointer is at the end of a TextStream file; False if it is not.

Syntax

object.AtEndOfStream

The object is always the name of a TextStream object.

Remarks

The AtEndOfStream property applies only to TextStream files that are open for reading; otherwise, an error occurs.

The following code illustrates the use of the AtEndOfStream property:

Copy code Copy code
Dim fs, a, retstring
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile("c:\testfile.txt", ForReading, False)
Do While a. AtEndOfStream <> True
    retstring = a.ReadLine
    ...
Loop
a.Close


Attributes Property

 Copy code hover
[image]

Attributes Property
Send feedback

Description

Sets or returns the attributes of files or folders. Read/write or read-only, depending on the attribute.

Syntax

object.Attributes [= newattributes]

The Attributes property has these parts:

Part | Description
object | Required. Always the name of a File or Folder object.
newattributes | Optional. If provided, newattributes is the new value for the attributes of the specified object.

Settings

The newattributes argument can have any of the following values or any logical combination of the following values:

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

Remarks

The following code illustrates the use of the Attributes property with a file:

Copy code Copy code
Sub SetClearArchiveBit(filespec)
    Dim fs, f, r
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(fs.GetFileName(filespec))
    If f.attributes and 32 Then
        r = MsgBox("The Archive bit is set, do you want to clear it?", vbYesNo, "Set/Clear Archive Bit")
        If r = vbYes Then
            f.attributes = f.attributes - 32
            MsgBox "Archive bit is cleared."
        Else
            MsgBox "Archive bit remains set."
        End If
    Else
        r = MsgBox("The Archive bit is not set. Do you want to set it?", vbYesNo, "Set/Clear Archive Bit")
        If r = vbYes Then
f.attributes = f.attributes + 32
            MsgBox "Archive bit is set."
        Else
            MsgBox "Archive bit remains clear."
        End If
    End If
End Sub


AvailableSpace Property

 Copy code hover
[image]

AvailableSpace Property
Send feedback

Description

Returns the amount of space available to a user on the specified drive or network share.

Syntax

object.AvailableSpace

The object is always a Drive object.

Remarks

The value returned by the AvailableSpace property is typically the same as that returned by the FreeSpace property. Differences may occur between the two values for computer systems that support quotas.

The following code illustrates the use of the AvailableSpace property:

Copy code Copy code
Sub ShowAvailableSpace(drvPath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(drvPath))
    s = "Drive " & UCase(drvPath) & " - "
    s = s & d.VolumeName  & vbCrLf
    s = s & "Available Space: " & FormatNumber(d.AvailableSpace/1024, 0)
    s = s & " Kbytes"
    MsgBox s
End Sub


Calendar Property

 Copy code hover
[image]

Calendar Property
Send feedback

Returns or sets a value specifying the type of calendar to use with your project.

You can use one of two settings for Calendar:

Setting | Value | Description
vbCalGreg | 0 | Use Gregorian calendar (default).
vbCalHijri | 1 | Use Hijri calendar.

Remarks

You can only set the Calendar property programmatically. For example, to use the Hijri calendar, use:

Copy code Copy code
Calendar = vbCalHijri


Column Property (Visual Basic for Applications)

 Copy code hover
[image]

Column Property (Visual Basic for Applications)
Send feedback

Description

Read-only property that returns the column number of the current character position in a TextStream file.

Syntax

object .Column

The object is always the name of a TextStream object.

Remarks

After a newline character has been written, but before any other character is written, Column is equal to 1.


CompareMode Property

 Copy code hover
[image]

CompareMode Property
Send feedback

Description

Sets and returns the comparison mode for comparing string keys in a Dictionary object.

Syntax

object.CompareMode[ = compare]

The CompareMode property has the following parts:

Part | Description
object | Required. Always the name of a Dictionary object.
compare | Optional. If provided, compare is a value representing the comparison mode used by functions such as StrComp.

Settings

The compare argument can have the following values:

Constant | Value | Description
vbUseCompareOption | -1 | Performs a comparison using the setting of the Option Compare statement.
vbBinaryCompare | 0 | Performs a binary comparison.
vbTextCompare | 1 | Performs a textual comparison.
vbDatabaseCompare | 2 | Microsoft Access only. Performs a comparison based on information in your database.

Remarks

An error occurs if you try to change the comparison mode of a Dictionary object that already contains data.

The CompareMode property uses the same values as the compare argument for the StrComp function. Values greater than 2 can be used to refer to comparisons using specific Locale IDs (LCID).


Count Property (FileSystemObject object)

 Copy code hover
[image]

Count Property (FileSystemObject object)
Send feedback

Description

Returns the number of items in a collection or Dictionary object. Read-only.

Syntax

object.Count

The object is always the name of one of the items in the Applies To list.

Remarks

The following code illustrates use of the Count property:

Copy code Copy code
Dim a, d, i             'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Keys              'Get the keys
For i = 0 To d.Count -1 'Iterate the array
    Print a(i)          'Print key
Next
...


Count Property (Visual Basic for Applications)

 Copy code hover
[image]

Count Property (Visual Basic for Applications)
Send feedback

Returns a Long (long integer) containing the number of objects in a collection. Read-only.

Example

This example uses the Collection object's Count property to specify how many iterations are required to remove all the elements of the collection called MyClasses. When collections are numerically indexed, the base is 1 by default. Since collections are reindexed automatically when a removal is made, the following code removes the first member on each iteration.

Copy code Copy code
Dim Num, MyClasses
For Num = 1 To MyClasses. Count    ' Remove name from the collection.
    MyClasses.Remove 1    ' Default collection numeric indexes
Next    ' begin at 1.


DateCreated Property

 Copy code hover
[image]

DateCreated Property
Send feedback

Description

Returns the date and time that the specified file or folder was created. Read-only.

Syntax

object.DateCreated

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the DateCreated property with a file:

Copy code Copy code
Sub ShowFileInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = "Created: " & f.DateCreated
    MsgBox s
End Sub


DateLastAccessed Property

 Copy code hover
[image]

DateLastAccessed Property
Send feedback

Description

Returns the date and time that the specified file or folder was last accessed. Read-only.

Syntax

object.DateLastAccessed

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the DateLastAccessed property with a file:

Copy code Copy code
Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(filespec) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

Important note Important

This method depends on the underlying operating system for its behavior. If the operating system does not support providing time information, none will be returned.


DateLastModified Property

 Copy code hover
[image]

DateLastModified Property
Send feedback

Description

Returns the date and time that the specified file or folder was last modified. Read-only.

Syntax

object.DateLastModified

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the DateLastModified property with a file:

Copy code Copy code
Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(filespec) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub


Description Property (Visual Basic for Applications)

 Copy code hover
[image]

Description Property (Visual Basic for Applications)
Send feedback

Returns or sets a string expression containing a descriptive string associated with an object. Read/write.

For the Err object, returns or sets a descriptive string associated with an error.

Remarks

The Description property setting consists of a short description of the error. Use this property to alert the user to an error that you either can't or don't want to handle. When generating a user-defined error, assign a short description of your error to the Description property. If Description isn't filled in, and the value of Number corresponds to a Visual Basic run-time error, the string returned by the Error function is placed in Description when the error is generated.

Example

This example assigns a user-defined message to the Description property of the Err object.

Copy code Copy code
Err. Description = "It was not possible to access an object necessary " _
& "for this operation."


Drive Property

 Copy code hover
[image]

Drive Property
Send feedback

Description

Returns the drive letter of the drive on which the specified file or folder resides. Read-only.

Syntax

object.Drive

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the Drive property:

Copy code Copy code
Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = f.Name & " on Drive " & UCase(f.Drive) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub


DriveLetter Property

 Copy code hover
[image]

DriveLetter Property
Send feedback

Description

Returns the drive letter of a physical local drive or a network share. Read-only.

Syntax

object.DriveLetter

The object is always a Drive object.

Remarks

The DriveLetter property returns a zero-length string ("") if the specified drive is not associated with a drive letter, for example, a network share that has not been mapped to a drive letter.

The following code illustrates the use of the DriveLetter property:

Copy code Copy code
Sub ShowDriveLetter(drvPath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(drvPath))
    s = "Drive " & d.DriveLetter & ": - "
    s = s & d.VolumeName  & vbCrLf
    s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
    s = s & " Kbytes"
    MsgBox s
End Sub


Drives Property

 Copy code hover
[image]

Drives Property
Send feedback

Description

Returns a Drives collection consisting of all Drive objects available on the local machine.

Syntax

object.Drives

The object is always a FileSystemObject.

Remarks

Removable-media drives need not have media inserted for them to appear in the Drives collection.

You can iterate the members of the Drives collection using a For Each...Next construct as illustrated in the following code:

Copy code Copy code
Sub ShowDriveList
    Dim fs, d, dc, s, n
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set dc = fs.Drives
    For Each d in dc
        s = s & d.DriveLetter & " - "
        If d.DriveType = 3 Then
            n = d.ShareName
        Else
            n = d.VolumeName
        End If
        s = s & n & vbCrLf
    Next
    MsgBox s
End Sub


DriveType Property

 Copy code hover
[image]

DriveType Property
Send feedback

Description

Returns a value indicating the type of a specified drive.

Syntax

object.DriveType

The object is always a Drive object.

Remarks

The following code illustrates the use of the DriveType property:

Copy code Copy code
Sub ShowDriveType(drvpath)
    Dim fs, d, s, t
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(drvpath)
    Select Case d.DriveType
        Case 0: t = "Unknown"
        Case 1: t = "Removable"
        Case 2: t = "Fixed"
        Case 3: t = "Network"
        Case 4: t = "CD-ROM"
        Case 5: t = "RAM Disk"
    End Select
    s = "Drive " & d.DriveLetter & ": - " & t
    MsgBox s
End Sub


Files Property

 Copy code hover
[image]

Files Property
Send feedback

Description

Returns a Files collection consisting of all File objects contained in the specified folder, including those with hidden and system file attributes set.

Syntax

object.Files

The object is always a Folder object.

Remarks

The following code illustrates the use of the Files property:

Copy code Copy code
Sub ShowFileList(folderspec)
    Dim fs, f, f1, fc, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set fc = f.Files
    For Each f1 in fc
        s = s & f1.name
        s = s &  vbCrLf
    Next
    MsgBox s
End Sub


FileSystem Property

 Copy code hover
[image]

FileSystem Property
Send feedback

Description

Returns the type of file system in use for the specified drive.

Syntax

object.FileSystem

The object is always a Drive object.

Remarks

Available return types include FAT, NTFS, and CDFS.

The following code illustrates the use of the FileSystem property:

Copy code Copy code
Sub ShowFileSystemType
    Dim fs,d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive("e:")
    s = d.FileSystem
    MsgBox s
End Sub


FreeSpace Property

 Copy code hover
[image]

FreeSpace Property
Send feedback

Description

Returns the amount of free space available to a user on the specified drive or network share. Read-only.

Syntax

object.FreeSpace

The object is always a Drive object.

Remarks

The value returned by the FreeSpace property is typically the same as that returned by the AvailableSpace property. Differences may occur between the two for computer systems that support quotas.

The following code illustrates the use of the FreeSpace property:

Copy code Copy code
Sub ShowFreeSpace(drvPath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(drvPath))
    s = "Drive " & UCase(drvPath) & " - "
    s = s & d.VolumeName  & vbCrLf
    s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
    s = s & " Kbytes"
    MsgBox s
End Sub


HelpContext Property (Visual Basic for Applications)

 Copy code hover
[image]

HelpContext Property (Visual Basic for Applications)
Send feedback

Returns or sets a string expression containing the context ID for a topic in a Help file. Read/write.

Remarks

The HelpContext property is used to automatically display the Help topic specified in the HelpFile property. If both HelpFile and HelpContext are empty, the value of Number is checked. If Number corresponds to a Visual Basic run-time error value, then the Visual Basic Help context ID for the error is used. If the Number value doesn't correspond to a Visual Basic error, the contents screen for the Visual Basic Help file is displayed.

Note Note

You should write routines in your application to handle typical errors. When programming with an object, you can use the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error isn't recoverable.

Example

This example uses the HelpContext property of the Err object to show the Visual Basic Help topic for the Overflow error.

Copy code Copy code
Dim Msg
Err.Clear
On Error Resume Next
Err.Raise 6 ' Generate "Overflow" error.
If Err.Number <> 0 Then
    Msg = "Press F1 or HELP to see " & Err.HelpFile & " topic for" & _
    " the following HelpContext: " & Err. HelpContext
    MsgBox Msg, , "Error: " & Err.Description, Err.HelpFile, _
Err.HelpContext
End If


HelpFile Property

 Copy code hover
[image]

HelpFile Property
Send feedback

Returns or sets a string expression the fully qualified path to a Help file. Read/write.

Remarks

If a Help file is specified in HelpFile, it is automatically called when the user presses the Help button (or the F1 KEY in Windows or the HELP key on the Macintosh) in the error message dialog box. If the HelpContext property contains a valid context ID for the specified file, that topic is automatically displayed. If no HelpFile is specified, the Visual Basic Help file is displayed.

Note Note

You should write routines in your application to handle typical errors. When programming with an object, you can use the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error isn't recoverable.

Example

This example uses the HelpFile property of the Err object to start the Help system. By default, the HelpFile property contains the name of the Visual Basic Help file.

Copy code Copy code
Dim Msg
Err.Clear
On Error Resume Next    ' Suppress errors for demonstration purposes.
Err.Raise 6    ' Generate "Overflow" error.
Msg = "Press F1 or HELP to see " & Err. HelpFile & _
" topic for this error"
MsgBox Msg, , "Error: " & Err.Description,Err. HelpFile


IsReady Property

 Copy code hover
[image]

IsReady Property
Send feedback

Description

Returns True if the specified drive is ready; False if it is not.

Syntax

object.IsReady

The object is always a Drive object.

Remarks

For removable-media drives and CD-ROM drives, IsReady returns True only when the appropriate media is inserted and ready for access.

The following code illustrates the use of the IsReady property:

Copy code Copy code
Sub ShowDriveInfo(drvpath)
    Dim fs, d, s, t
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(drvpath)
    Select Case d.DriveType
        Case 0: t = "Unknown"
        Case 1: t = "Removable"
        Case 2: t = "Fixed"
        Case 3: t = "Network"
        Case 4: t = "CD-ROM"
        Case 5: t = "RAM Disk"
    End Select
    s = "Drive " & d.DriveLetter & ": - " & t
    If d.IsReady Then
        s = s & vbCrLf & "Drive is Ready."
    Else
        s = s & vbCrLf & "Drive is not Ready."
    End If
    MsgBox s
End Sub


IsRootFolder Property

 Copy code hover
[image]

IsRootFolder Property
Send feedback

Description

Returns True if the specified folder is the root folder; False if it is not.

Syntax

object.IsRootFolder

The object is always a Folder object.

Remarks

The following code illustrates the use of the IsRootFolder property:

Copy code Copy code
Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")
Sub DisplayLevelDepth(pathspec)
    Dim f, n
    Set f = fs.GetFolder(pathspec)
    If f.IsRootFolder Then
        MsgBox "The specified folder is the root folder."
    Else
        Do Until f.IsRootFolder
            Set f = f.ParentFolder
            n = n + 1
        Loop
        MsgBox "The specified folder is nested " & n & " levels deep."
    End If
End Sub


Item Property (FileSystemObject object)

 Copy code hover
[image]

Item Property (FileSystemObject object)
Send feedback

Description

Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write.

Syntax

object.Item(key) [= newitem]

The Item property has the following parts:

Part | Description
object | Required. Always the name of a collection or Dictionary object.
key | Required. Key associated with the item being retrieved or added.
newitem | Optional. Used for Dictionary object only; no application for collections. If provided, newitem is the new value associated with the specified key.

Remarks

If key is not found when changing an item, a new key is created with the specified newitem. If key is not found when attempting to return an existing item, a new key is created and its corresponding item is left empty.


Key Property

 Copy code hover
[image]

Key Property
Send feedback

Description

Sets a key in a Dictionary object.

Syntax

object.Key(key) = newkey

The Key property has the following parts:

Part | Description
object | Required. Always the name of a Dictionary object.
key | Required. Key value being changed.
newkey | Required. New value that replaces the specified key.

Remarks

If key is not found when changing a key, a run-time error will occur.


LastDLLError Property

 Copy code hover
[image]

LastDLLError Property
Send feedback

Returns a system error code produced by a call to a dynamic-link library (DLL). Read-only. LastDLLError always returns zero on the Macintosh.

Remarks

The LastDLLError property applies only to DLL calls made from Visual Basic code. When such a call is made, the called function usually returns a code indicating success or failure, and the LastDLLError property is filled. Check the documentation for the DLL's functions to determine the return values that indicate success or failure. Whenever the failure code is returned, the Visual Basic application should immediately check the LastDLLError property. No exception is raised when the LastDLLError property is set.

Example

When pasted into a UserForm module, the following code causes an attempt to call a DLL function. The call fails because the argument that is passed in (a null pointer) generates an error, and in any event, SQL can't be cancelled if it isn't running. The code following the call checks the return of the call, and then prints at the LastDLLError property of the Err object to reveal the error code. On systems without DLLs, LastDLLError always returns zero.

Copy code Copy code
Private Declare Function SQLCancel Lib "ODBC32.dll" _
 (ByVal hstmt As Long) As Integer

Private Sub UserForm_Click()
    Dim RetVal
    ' Call with invalid argument.
    RetVal = SQLCancel(myhandle&)
    ' Check for SQL error code.
    If RetVal = -2 Then
        'Display the information code.
        MsgBox "Error code is :" & Err. LastDllError
    End If
End Sub


Line Property

 Copy code hover
[image]

Line Property
Send feedback

Description

Read-only property that returns the current line number in a TextStream file.

Syntax

object.Line

The object is always the name of a TextStream object.

Remarks

After a file is initially opened and before anything is written, Line is equal to 1.


Name Property (FileSystemObject object)

 Copy code hover
[image]

Name Property (FileSystemObject object)
Send feedback

Description

Sets or returns the name of a specified file or folder. Read/write.

Syntax

object.Name [= newname]

The Name property has these parts:

Part | Description
object | Required. Always the name of a File or Folder object.
newname | Optional. If provided, newname is the new name of the specified object.

Remarks

The following code illustrates the use of the Name property:

Copy code Copy code
Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = f.Name & " on Drive " & UCase(f.Drive) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub


Number Property (Visual Basic for Applications)

 Copy code hover
[image]

Number Property (Visual Basic for Applications)
Send feedback

Returns or sets a numeric value specifying an error. Number is the Err object's default property. Read/write.

Remarks

When returning a user-defined error from an object, set Err.Number by adding the number you selected as an error code to the vbObjectError constant. For example, you use the following code to return the number 1051 as an error code:

Copy code Copy code
Err.Raise Number := vbObjectError + 1051, Source:= "SomeClass"

Example

The first example illustrates a typical use of the Number property in an error-handling routine. The second example examines the Number property of the Err object to determine whether an error returned by an Automation object was defined by the object, or whether it was mapped to an error defined by Visual Basic. Note that the constant vbObjectError is a very large negative number that an object adds to its own error code to indicate that the error is defined by the server. Therefore, subtracting it from Err.Number strips it out of the result. If the error is object-defined, the base number is left in MyError, which is displayed in a message box along with the original source of the error. If Err.Number represents a Visual Basic error, then the Visual Basic error number is displayed in the message box.

Copy code Copy code
' Typical use of Number property
Sub test()
    On Error GoTo out

    Dim x, y
    x = 1 / y    ' Create division by zero error
    Exit Sub
    out:
    MsgBox Err. Number
    MsgBox Err.Description
    ' Check for division by zero error
    If Err.Number = 11 Then
        y = y + 1
    End If
    Resume
End Sub

' Using Number property with an error from an
' Automation object
Dim MyError, Msg
' First, strip off the constant added by the object to indicate one
' of its own errors.
MyError = Err. Number - vbObjectError
' If you subtract the vbObjectError constant, and the number is still
' in the range 0-65,535, it is an object-defined error code.
If MyError > 0 And MyError < 65535 Then
    Msg = "The object you accessed assigned this number to the error: " _
             & MyError & ". The originator of the error was: " _
            & Err.Source & ". Press F1 to see originator's Help topic."
' Otherwise it is a Visual Basic error number.
Else
    Msg = "This error (# " & Err. Number & ") is a Visual Basic error" & _
            " number. Press Help button or F1 for the Visual Basic Help" _
            & " topic for this error."
End If
    MsgBox Msg, , "Object Error", Err.HelpFile, Err.HelpContext


ParentFolder Property

 Copy code hover
[image]

ParentFolder Property
Send feedback

Description

Returns the folder object for the parent of the specified file or folder. Read-only.

Syntax

object.ParentFolder

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the ParentFolder property with a file:

Copy code Copy code
Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(f.Name) & " in " & UCase(f.ParentFolder) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub


Path Property (FileSystemObject object)

 Copy code hover
[image]

Path Property (FileSystemObject object)
Send feedback

Description

Returns the path for a specified file, folder, or drive.

Syntax

object.Path

The object is always a File, Folder, or Drive object.

Remarks

For drive letters, the root drive is not included. For example, the path for the C drive is C:, not C:\.

The following code illustrates the use of the Path property with a File object:

Copy code Copy code
Sub ShowFileAccessInfo(filespec)
    Dim fs, d, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(f.Path) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub


RightToLeft Property

 Copy code hover
[image]

RightToLeft Property
Send feedback

Returns a Boolean value that indicates the text display direction and controls the visual appearance on a bidirectional system.

Remarks

The settings for the RightToLeft property are:

Setting | Description
True | The control is running on a bidirectional platform, such as Arabic Windows95 or Hebrew Windows95, and text is running from right to left. The control should modify its behavior, such as putting vertical scroll bars at the left side of a text or list box, putting labels to the right of text boxes, and so forth.
False | The control should act as though it was running on a non-bidirectional platform, such as English Windows95, and text is running from left to right. If the container does not implement this ambient property, False is the default value.

The RightToLeft property holds ambient information from the Userform that suggests behavior to controls contained within the UserForm. This property is a Boolean that indicates text display direction and controls visual appearance on bidirectional systems. The default is False.


RootFolder Property

 Copy code hover
[image]

RootFolder Property
Send feedback

Description

Returns a Folder object representing the root folder of a specified drive. Read-only.

Syntax

object.RootFolder

The object is always a Drive object.

Remarks

All the files and folders contained on the drive can be accessed using the returned Folder object.


SerialNumber Property

 Copy code hover
[image]

SerialNumber Property
Send feedback

Description

Returns the decimal serial number used to uniquely identify a disk volume.

Syntax

object.SerialNumber

The object is always a Drive object.

Remarks

You can use the SerialNumber property to ensure that the correct disk is inserted in a drive with removable media.

The following code illustrates the use of the SerialNumber property:

Copy code Copy code
Sub ShowDriveInfo(drvpath)
    Dim fs, d, s, t
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(fs.GetAbsolutePathName(drvpath)))
    Select Case d.DriveType
        Case 0: t = "Unknown"
        Case 1: t = "Removable"
        Case 2: t = "Fixed"
        Case 3: t = "Network"
        Case 4: t = "CD-ROM"
        Case 5: t = "RAM Disk"
    End Select
    s = "Drive " & d.DriveLetter & ": - " & t
    s = s & vbCrLf & "SN: " & d.SerialNumber
    MsgBox s
End Sub


ShareName Property

 Copy code hover
[image]

ShareName Property
Send feedback

Description

Returns the network share name for a specified drive.

Syntax

object.ShareName

The object is always a Drive object.

Remarks

If object is not a network drive, the ShareName property returns a zero-length string ("").

The following code illustrates the use of the ShareName property:

Copy code Copy code
Sub ShowDriveInfo(drvpath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(fs.GetAbsolutePathName(drvpath)))
    s = "Drive " & d.DriveLetter & ": - " & d.ShareName
    MsgBox s
End Sub


ShortName Property

 Copy code hover
[image]

ShortName Property
Send feedback

Description

Returns the short name used by programs that require the earlier 8.3 naming convention.

Syntax

object.ShortName

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the ShortName property with a File object:

Copy code Copy code
Sub ShowShortName(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = "The short name for " & "" & UCase(f.Name)
    s = s & "" & vbCrLf
    s = s & "is: " & "" & f.ShortName & ""
    MsgBox s, 0, "Short Name Info"
End Sub


ShortPath Property

 Copy code hover
[image]

ShortPath Property
Send feedback

Description

Returns the short path used by programs that require the earlier 8.3 file naming convention.

Syntax

object.ShortPath

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the ShortName property with a File object:

Copy code Copy code
Sub ShowShortPath(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = "The short path for " & "" & UCase(f.Name)
    s = s & "" & vbCrLf
    s = s & "is: " & "" & f.ShortPath & ""
    MsgBox s, 0, "Short Path Info"
End Sub


ShowModal Property

 Copy code hover
[image]

ShowModal Property
Send feedback

Sets a UserForm to be modal or modeless in its display. Read-only at run time.

Remarks

The settings for the ShowModal property are:

Setting | Description
True | (Default) The UserForm is modal.
False | The UserForm is modeless.

Remarks

When a UserForm is modal, the user must supply information or close the UserForm before using any other part of the application. No subsequent code is executed until the UserForm is hidden or unloaded. Although other forms in the application are disabled when a UserForm is displayed, other applications are not.

When the UserForm is modeless, the user can view other forms or windows without closing the UserForm.

Modeless forms do not appear in the task bar and are not in the window tab order.

Note Note

If you attempt to open a UserForm that has a ShowModal property in Microsoft Office 97, you get a run-time error because Office 97 only displays modal UserForms. Office 97 ignores the ShowModal property and displays the UserForm modally.


Size Property (FileSystemObject object)

 Copy code hover
[image]

Size Property (FileSystemObject object)
Send feedback

Description

For files, returns the size, in bytes, of the specified file. For folders, returns the size, in bytes, of all files and subfolders contained in the folder.

Syntax

object.Size

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the Size property with a Folder object:

Copy code Copy code
Sub ShowFolderSize(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(filespec)
    s = UCase(f.Name) & " uses " & f.size & " bytes."
    MsgBox s, 0, "Folder Size Info"
End Sub


Source Property (Visual Basic for Applications)

 Copy code hover
[image]

Source Property (Visual Basic for Applications)
Send feedback

Returns or sets a string expression specifying the name of the object or application that originally generated the error. Read/write.

Remarks

The Source property specifies a string expression representing the object that generated the error; the expression is usually the object's class name or programmatic ID. Use Source to provide information when your code is unable to handle an error generated in an accessed object. For example, if you access Microsoft Excel and it generates a Division by zero error, Microsoft Excel sets Err.Number to its error code for that error and sets Source to Excel.Application.

When generating an error from code, Source is your application's programmatic ID. For class modules, Source should contain a name having the form project.class. When an unexpected error occurs in your code, the Source property is automatically filled in. For errors in a standard module, Source contains the project name. For errors in a class module, Source contains a name with the project.class form.

Example

This example assigns the Programmatic ID of an Automation object created in Visual Basic to the variable MyObjectID, and then assigns that to the Source property of the Err object when it generates an error with the Raise method. When handling errors, you should not use the Source property (or any Err properties other than Number) programmatically. The only valid use of properties other than Number is for displaying rich information to an end user in cases where you can't handle an error. The example assumes that App and MyClass are valid references.

VBA Copy code Copy code
Dim MyClass, MyObjectID, MyHelpFile, MyHelpContext
' An object of type MyClass generates an error and fills all Err object
' properties, including Source, which receives MyObjectID, which is a
' combination of the Title property of the App object and the Name
' property of the MyClass object.
MyObjectID = App.Title & "." & MyClass.Name
Err. Raise    Number := vbObjectError + 894, Source := MyObjectID, _
                Description := "Was not able to complete your task", _
                HelpFile := MyHelpFile, HelpContext := MyHelpContext


StartUpPosition Property

 Copy code hover
[image]

StartUpPosition Property
Send feedback

Returns or sets a value specifying the position of a UserForm when it first appears.

You can use one of four settings for StartUpPosition:

Setting | Value | Description
Manual | 0 | No initial setting specified.
CenterOwner | 1 | Center on the item to which the UserForm belongs.
CenterScreen | 2 | Center on the whole screen.
WindowsDefault | 3 | Position in upper-left corner of screen.

Remarks

You can set the StartUpPosition property programmatically or from the Properties window.

Example

The following example uses the Load statement and the Show method in UserForm1's Click event to load UserForm2 with the StartUpPosition property set to 3 (the Windows default position). The Show method then makes UserForm2 visible.

Copy code Copy code
Private Sub UserForm_Click()
    Load UserForm2
    UserForm2. StartUpPosition = 3
    UserForm2.Show
End Sub


SubFolders Property

 Copy code hover
[image]

SubFolders Property
Send feedback

Description

Returns a Folders collection consisting of all folders contained in a specified folder, including those with Hidden and System file attributes set.

Syntax

object.SubFolders

The object is always a Folder object.

Remarks

The following code illustrates the use of the SubFolders property:

Copy code Copy code
Sub ShowFolderList(folderspec)
    Dim fs, f, f1, s, sf
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set sf = f.SubFolders
    For Each f1 in sf
        s = s & f1.name
        s = s &  vbCrLf
    Next
    MsgBox s
End Sub


TotalSize Property

 Copy code hover
[image]

TotalSize Property
Send feedback

Description

Returns the total space, in bytes, of a drive or network share.

Syntax

object.TotalSize

The object is always a Drive object.

Remarks

The following code illustrates the use of the TotalSize property:

Copy code Copy code
Sub ShowSpaceInfo(drvpath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(fs.GetAbsolutePathName(drvpath)))
    s = "Drive " & d.DriveLetter & ":"
    s = s & vbCrLf
    s = s & "Total Size: " & FormatNumber(d.TotalSize/1024, 0) & " Kbytes"
    s = s & vbCrLf
    s = s & "Available: " & FormatNumber(d.AvailableSpace/1024, 0) & " Kbytes"
    MsgBox s
End Sub


Type Property (FileSystemObject object)

 Copy code hover
[image]

Type Property (FileSystemObject object)
Send feedback

Description

Returns information about the type of a file or folder. For example, for files ending in .TXT, "Text Document" is returned.

Syntax

object.Type

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the Type property to return a folder type. In this example, try providing the path of the Recycle Bin or other unique folder to the procedure.

Copy code Copy code
Sub ShowFileSize(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(filespec)
    s = UCase(f.Name) & " is a " & f.Type
    MsgBox s, 0, "File Size Info"
End Sub


VBComponents Property

 Copy code hover
[image]

VBComponents Property
Send feedback

Returns a collection of the components contained in a project.

Remarks

Use the VBComponents collection to access, add, or remove components in a project. A component can be a form, module, or class. The VBComponents collection is a standard collection that can be used in a For… Each block.

You can use the Parent property to return the project the VBComponents collection is in.

In Visual Basic for Applications, you can use the Import method to add a component to a project from a file.


VolumeName Property

 Copy code hover
[image]

VolumeName Property
Send feedback

Description

Sets or returns the volume name of the specified drive. Read/write.

Syntax

object.VolumeName [= newname]

The VolumeName property has these parts:

Part | Description
object | Required. Always the name of a Drive object.
newname | Optional. If provided, newname is the new name of the specified object.

Remarks

The following code illustrates the use of the VolumeName property:

Copy code Copy code
Sub ShowVolumeInfo(drvpath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(fs.GetAbsolutePathName(drvpath)))
    s = "Drive " & d.DriveLetter & ": - " & d.VolumeName
    MsgBox s
End Sub


WhatsThisButton Property

 Copy code hover
[image]

WhatsThisButton Property
Send feedback

Returns a Boolean value that determines whether the What's This button appears on the title bar of a UserForm object. Read-only at run time. This property does not apply to the Macintosh.

Remarks

The settings for the WhatsThisButton property are:

Setting | Description
True | Turns on display of the What's This Help button.
False | (Default) Turns off display of the What's This Help button.

Remarks

The WhatsThisHelp property must be True for the WhatsThisButton property to be True.


WhatsThisHelp Property

 Copy code hover
[image]

WhatsThisHelp Property
Send feedback

Returns a Boolean value that determines whether context-sensitive Help uses the pop-up window provided by Windows 95 Help or the main Help window. Read-only at run time. This property does not apply to the Macintosh.

Remarks

The settings for the WhatsThisHelp property are:

Setting | Description
True | The application uses one of the What's This access techniques to start Windows Help and load a topic identified by the WhatsThisHelpID property.
False | (Default) The application uses the F1 key to start Windows Help and load the topic identified by the HelpContextID property.

Remarks

There are two access techniques for providing What's This Help in an application. The WhatsThisHelp property must be set to True for any of these techniques to work.

  • Providing a What's This button on the title bar of the UserForm using the WhatsThisButton property. The mouse pointer changes to the What's This state (arrow with question mark). The topic displayed is identified by the WhatsThisHelpID property of the control clicked by the user.

  • Invoking the WhatsThisMode method of a UserForm. This produces the same behavior as clicking the What's This button without using a button. For example, you can invoke this method from a command on a menu in the menu bar of the application.


Statements

 Copy code hover
[image]

Statements
Send feedback

In this section

  • AppActivate Statement

  • Beep Statement

  • Call Statement

  • ChDir Statement

  • ChDrive Statement

  • Close Statement

  • Const Statement

  • Date Statement

  • Declare Statement

  • DeleteSetting Statement

  • Dim Statement

  • Do...Loop Statement

  • End Statement

  • Enum Statement

  • Erase Statement

  • Error Statement

  • Event Statement

  • Exit Statement

  • FileCopy Statement

  • For Each...Next Statement

  • For...Next Statement

  • Function Statement

  • Get Statement

  • GoSub...Return Statement

  • GoTo Statement

  • If...Then...Else Statement

  • Implements Statement

  • Input # Statement

  • Kill Statement

  • Let Statement

  • Line Input # Statement

  • Load Statement

  • Lock, Unlock Statements

  • LSet Statement

  • Mid Statement

  • MkDir Statement

  • Name Statement

  • On Error Statement

  • On...GoSub, On...GoTo Statements

  • Open Statement

  • Option Base Statement

  • Option Compare Statement

  • Option Explicit Statement

  • Option Private Statement

  • Print # Statement

  • Private Statement

  • Property Get Statement

  • Property Let Statement

  • Property Set Statement

  • Public Statement

  • Put Statement

  • RaiseEvent Statement

  • Randomize Statement

  • ReDim Statement

  • Rem Statement

  • Reset Statement

  • Resume Statement

  • RmDir Statement

  • RSet Statement

  • SaveSetting Statement

  • Seek Statement

  • Select Case Statement

  • SendKeys Statement

  • Set Statement

  • SetAttr Statement

  • Static Statement

  • Stop Statement

  • Sub Statement

  • Time Statement

  • Type Statement

  • Unload Statement

  • While...Wend Statement

  • Width # Statement

  • With Statement

  • Write # Statement

  • Deftype Statements


AppActivate Statement

 Copy code hover
[image]

AppActivate Statement
Send feedback

Activates an application window.

Syntax

AppActivate title [, wait]

The AppActivate statement syntax has these named arguments:

Part | Description
title | Required. String expression specifying the title in the title bar of the application window you want to activate. The task ID returned by the Shell function can be used in place of title to activate an application.
wait | Optional. Boolean value specifying whether the calling application has the focus before activating another. If False (default), the specified application is immediately activated, even if the calling application does not have the focus. If True, the calling application waits until it has the focus, then activates the specified application.

Remarks

The AppActivate statement changes the focus to the named application or window but does not affect whether it is maximized or minimized. Focus moves from the activated application window when the user takes some action to change the focus or close the window. Use the Shell function to start an application and set the window style.

In determining which application to activate, title is compared to the title string of each running application. If there is no exact match, any application whose title string begins with title is activated. If there is more than one instance of the application named by title, one instance is arbitrarily activated.

Example

This example illustrates various uses of the AppActivate statement to activate an application window. The Shell statements assume the applications are in the paths specified. On the Macintosh, the default drive name is "HD" and portions of the pathname are separated by colons instead of backslashes.

Copy code Copy code
Dim MyAppID, ReturnValue
AppActivate "Microsoft Word" ' Activate Microsoft
 ' Word.

' AppActivate can also use the return value of the Shell function.
MyAppID = Shell("C:\WORD\WINWORD.EXE", 1) ' Run Microsoft Word.
AppActivate MyAppID ' Activate Microsoft
 ' Word.

' You can also use the return value of the Shell function.
ReturnValue = Shell("c:\EXCEL\EXCEL.EXE",1) ' Run Microsoft Excel.
AppActivate ReturnValue ' Activate Microsoft
 ' Excel.


Beep Statement

 Copy code hover
[image]

Beep Statement
Send feedback

Sounds a tone through the computer's speaker.

Syntax

Beep

Remarks

The frequency and duration of the beep depend on your hardware and system software, and vary among computers.

Example

This example uses the Beep statement to sound three consecutive tones through the computer's speaker.

Copy code Copy code
Dim I
For I = 1 To 3 ' Loop 3 times.
 Beep ' Sound a tone.
Next I


Call Statement

 Copy code hover
[image]

Call Statement
Send feedback

Transfers control to a Sub procedure, Function procedure, or dynamic-link library (DLL) procedure.

Syntax

[Call] name [argumentlist]

The Call statement syntax has these parts:

Part

Description

Call

Optional; keyword. If specified, you must enclose argumentlist in parentheses. For example:

Copy code Copy code
Call MyProc(0)

name

Required. Name of the procedure to call.

argumentlist

Optional. Comma-delimited list of variables, arrays, or expressions to pass to the procedure. Components of argumentlist may include the keywords ByVal or ByRef to describe how the arguments are treated by the called procedure. However, ByVal and ByRef can be used with Call only when calling a DLL procedure. On the Macintosh, ByVal and ByRef can be used with Call when making a call to a Macintosh code resource.

Remarks

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

To pass a whole array to a procedure, use the array name followed by empty parentheses.

Example

This example illustrates how the Call statement is used to transfer control to a Sub procedure, an intrinsic function, and a dynamic-link library (DLL) procedure.DLLs are not used on the Macintosh.

Copy code Copy code
' Call a Sub procedure.
Call PrintToDebugWindow("Hello World")
' The above statement causes control to be passed to the following
' Sub procedure.
Sub PrintToDebugWindow(AnyString)
    Debug.Print AnyString    ' Print to the Immediate window.
End Sub

' Call an intrinsic function. The return value of the function is
' discarded.
Call Shell(AppName, 1)    ' AppName contains the path of the
        ' executable file.

' Call a Microsoft Windows DLL procedure. The Declare statement must be
' Private in a Class Module, but not in a standard Module.
Private Declare Sub MessageBeep Lib "User" (ByVal N As Integer)
Sub CallMyDll()
    Call MessageBeep(0)    ' Call Windows DLL procedure.
    MessageBeep 0    ' Call again without Call keyword.
End Sub


ChDir Statement

 Copy code hover
[image]

ChDir Statement
Send feedback

Changes the current directory or folder.

Syntax

ChDir path

The required path argument is a string expression that identifies which directory or folder becomes the new default directory or folder. The path may include the drive. If no drive is specified, ChDir changes the default directory or folder on the current drive.

Remarks

The ChDir statement changes the default directory but not the default drive. For example, if the default drive is C, the following statement changes the default directory on drive D, but C remains the default drive:

Copy code Copy code
ChDir "D:\TMP"

On the Power Macintosh, the default drive always changes to the drive specified in path. Full path specifications begin with the volume name, and relative paths begin with a colon (:). ChDir resolves any aliases specified in the path:

Copy code Copy code
ChDir "MacDrive:Tmp" ' On the Macintosh.

Note that when making relative directory changes, different symbols are used in Microsoft Windows and on the Macintosh:

Copy code Copy code
ChDir ".." ' Moves up one directory in Microsoft Windows.
ChDir "::" ' Moves up one directory on the Macintosh.

Example

This example uses the ChDir statement to change the current directory or folder. On the Macintosh, the default drive name is "HD" and portions of the pathname are separated by colons instead of backslashes. Similarly, you would specify Macintosh folders instead of \Windows. Finally, wildcard characters have no special meaning on the Macintosh and are treated simply as characters.

Copy code Copy code
' Change current directory or folder to "MYDIR".
ChDir "MYDIR"

' Assume "C:" is the current drive. The following statement changes
' the default directory on drive "D:". "C:" remains the current drive.
ChDir "D:\WINDOWS\SYSTEM"


ChDrive Statement

 Copy code hover
[image]

ChDrive Statement
Send feedback

Changes the current drive.

Syntax

ChDrive drive

The required drive argument is a string expression that specifies an existing drive. If you supply a zero-length string (""), the current drive doesn't change. If the drive argument is a multiple-character string, ChDrive uses only the first letter.

On the Macintosh, ChDrive changes the current folder to the root folder of the specified drive.

Example

This example uses the ChDrive statement to change the current drive. On the Macintosh, "HD:" is the default drive name and ChDrive would change the current folder to the root folder of the specified drive. The following example assumes the machine actually has a drive named D.

Copy code Copy code
                      ChDrive "D" ' Make "D" the current drive.


Close Statement

 Copy code hover
[image]

Close Statement
Send feedback

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

Syntax

Close [filenumberlist]

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

[[#]filenumber] [, [#]filenumber] . . .

Remarks

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

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

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

Example

This example uses the Close statement to close all three files opened for Output.

Copy code Copy code
Dim I, FileName
For I = 1 To 3 ' Loop 3 times.
 FileName = "TEST" & I ' Create file name.
 Open FileName For Output As #I ' Open file.
 Print #I, "This is a test." ' Write string to file.
Next I
Close ' Close all 3 open files.


Const Statement

 Copy code hover
[image]

Const Statement
Send feedback

Declares constants for use in place of literal values.

Syntax

[Public | Private] Const constname [As type] = expression

The Const statement syntax has these parts:

Part | Description
Public | Optional. Keyword used at module level to declare constants that are available to all procedures in all modules. Not allowed in procedures.
Private | Optional. Keyword used at module level to declare constants that are available only within the module where the declaration is made. Not allowed in procedures.
constname | Required. Name of the constant; follows standard variable naming conventions.
type | Optional. Data type of the constant; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String, or Variant. Use a separate As type clause for each constant being declared.
expression | Required. Literal, other constant, or any combination that includes all arithmetic or logical operators except Is.

Remarks

Constants are private by default. Within procedures, constants are always private; their visibility can't be changed. In standard modules, the default visibility of module-level constants can be changed using the Public keyword. In class modules, however, constants can only be private and their visibility can't be changed using the Public keyword.

To combine several constant declarations on the same line, separate each constant assignment with a comma. When constant declarations are combined in this way, the Public or Private keyword, if used, applies to all of them.

You can't use variables, user-defined functions, or intrinsic Visual Basic functions (such as Chr) in expressions assigned to constants.

Note Note

Constants can make your programs self-documenting and easy to modify. Unlike variables, constants can't be inadvertently changed while your program is running.

If you don't explicitly declare the constant type using As type, the constant has the data type that is most appropriate for expression.

Constants declared in a Sub, Function, or Property procedure are local to that procedure. A constant declared outside a procedure is defined throughout the module in which it is declared. You can use constants anywhere you can use an expression.

Example

This example uses the Const statement to declare constants for use in place of literal values. Public constants are declared in the General section of a standard module, rather than a class module. Private constants are declared in the General section of any type of module.

Copy code Copy code
' Constants are Private by default.
Const MyVar = 459

' Declare Public constant.
Public Const MyString = "HELP"

' Declare Private Integer constant.
Private Const MyInt As Integer = 5

' Declare multiple constants on same line.
Const MyStr = "Hello", MyDouble As Double = 3.4567


Date Statement

 Copy code hover
[image]

Date Statement
Send feedback

Sets the current system date.

Syntax

Date = date

For systems running Microsoft Windows 95, the required date specification must be a date from January 1, 1980 through December 31, 2099. For systems running Microsoft Windows NT, date must be a date from January 1, 1980 through December 31, 2079. For the Macintosh, date must be a date from January 1, 1904 through February 5, 2040.

Example

This example uses the Date statement to set the computer system date. In the development environment, the date literal is displayed in short date format using the locale settings of your code.

Copy code Copy code
Dim MyDate
MyDate = #February 12, 1985# ' Assign a date.
Date = MyDate ' Change system date.


Declare Statement

 Copy code hover
[image]

Declare Statement
Send feedback

Used at module level to declare references to external procedures in a dynamic-link library (DLL).

Note Note

Declare statements with the PtrSafe keyword is the recommended syntax. Declare statements that include PtrSafe work correctly in the VBA7 development environment on both 32-bit and 64-bit platforms only after all data types in the Declare statement (parameters and return values) that need to store 64-bit quantities are updated to use LongLong for 64-bit integrals or LongPtr for pointers and handles. To ensure backwards compatibility with VBA version 6 and earlier use the following construct:
VBA Copy code Copy code
#If Vba7 Then
Declare PtrSafe Sub...
#Else
Declare Sub...
#EndIf

Syntax 1

[Public | Private] Declare Sub name Lib "libname" [Alias "aliasname"] [([arglist])]

Syntax 2

[Public | Private] Declare Function name Lib "libname" [Alias "aliasname"] [([arglist])] [As type]

VBA7 Declare Statement Syntax

Note Note

For code to run in 64-bit versions of Microsoft Office all Declare statements must include the PtrSafe keyword, and all data types in the Declare statement (parameters and return values) that need to store 64-bit quantities must be updated to use LongLong for 64-bit integrals or LongPtr for pointers and handles.

Syntax 1 (Sub)

[Public | Private] Declare PtrSafe Sub name Lib "libname" [Alias "aliasname"] [([arglist])]

Syntax 2 (Function)

[Public | Private] Declare PtrSafe Function name Lib "libname" [Alias "aliasname"] [([arglist])] [As type]

Part | Description
Public | Optional. Used to declare procedures that are available to all other procedures in all modules.
Private | Optional. Used to declare procedures that are available only within the module where the declaration is made.
PtrSafe | Required on 64-bit. The PtrSafe keyword asserts that a Declare statement is safe to run in 64-bit versions of Microsoft Office
Sub | Optional (either Sub or Function must appear). Indicates that the procedure doesn't return a value.
Function | Optional (either Sub or Function must appear). Indicates that the procedure returns a value that can be used in an expression.
name | Required. Any valid procedure name. Note that DLL entry points are case sensitive.
Lib | Required. Indicates that a DLL or code resource contains the procedure being declared. The Lib clause is required for all declarations.
libname | Required. Name of the DLL or code resource that contains the declared procedure.
Alias | Optional. Indicates that the procedure being called has another name in the DLL. This is useful when the external procedure name is the same as a keyword. You can also use Alias when a DLL procedure has the same name as a public variable, constant, or any other procedure in the same scope. Alias is also useful if any characters in the DLL procedure name aren't allowed by the DLL naming convention.
aliasname | Optional. Name of the procedure in the DLL or code resource. If the first character is not a number sign (#), aliasname is the name of the procedure's entry point in the DLL. If (#) is the first character, all characters that follow must indicate the ordinal number of the procedure's entry point.
arglist | Optional. List of variables representing arguments that are passed to the procedure when it is called.
type | Optional. Data type of the value returned by a Function procedure; may be Byte, Boolean, Integer, Long, LongLong, LongPtr, Currency, Single, Double, Decimal (not currently supported), Date, String (variable length only), or Variant, a user-defined type, or an object type. (LongLong is a valid declared type only on 64-bit platforms.)

The arglist argument has the following syntax and parts:

[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type]

Part | Description
Optional | Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used.
ByVal | Optional. Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.
ParamArray | Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. The ParamArray keyword can't be used with ByVal, ByRef, or Optional.
varname | Required. Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions.
( ) | Required for array variables. Indicates that varname is an array.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, LongLong, LongPtr, Currency, Single, Double, Decimal (not currently supported), Date, String (variable length only), Object, Variant, a user-defined type, or an object type. (LongLong is a valid declared type only on 64-bit platforms.)

Remarks

For Function procedures, the data type of the procedure determines the data type it returns. You can use an As clause following arglist to specify the return type of the function. Within arglist, you can use an As clause to specify the data type of any of the arguments passed to the procedure. In addition to specifying any of the standard data types, you can specify As Any in arglist to inhibit type checking and allow any data type to be passed to the procedure.

Empty parentheses indicate that the Sub or Function procedure has no arguments and that Visual Basic should ensure that none are passed. In the following example, First takes no arguments. If you use arguments in a call to takes no arguments. If you use arguments in a call to First , an error occurs:

Copy code Copy code
Declare Sub First Lib "MyLib" ()

If you include an argument list, the number and type of arguments are checked each time the procedure is called. In the following example, takes one Long argument:

Copy code Copy code
Declare Sub First Lib "MyLib" (X As Long)
Note Note

You can't have fixed-length strings in the argument list of a Declare statement; 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.
Note Note

The vbNullString constant is used when calling external procedures, where the external procedure requires a string whose value is zero. This is not the same thing as a zero-length string ("").

Example

This example shows how the Declare statement is used at the module level of a standard module to declare a reference to an external procedure in a dynamic-link library (DLL). You can place the Declare statements in class modules if the Declare statements are Private.

Note Note

Copy code Copy code
' In Microsoft Windows (16-bit):
Declare Sub MessageBeep Lib "User" (ByVal N As Integer)
' Assume SomeBeep is an alias for the procedure name.
Declare Sub MessageBeep Lib "User" Alias "SomeBeep"(ByVal N As Integer)
' Use an ordinal in the Alias clause to call GetWinFlags.
Declare Function GetWinFlags Lib "Kernel" Alias "#132"() As Long

' In 32-bit Microsoft Windows systems, specify the library USER32.DLL,
' rather than USER.DLL. You can use conditional compilation to write
' code that can run on either Win32 or Win16.
#If Win32 Then
    Declare Sub MessageBeep Lib "User32" (ByVal N As Long)
#Else
    Declare Sub MessageBeep Lib "User" (ByVal N As Integer)
#End If

' 64-bit Declare statement example:
Declare PtrSafe Function GetActiveWindow Lib "User32" () As LongPtr

' Conditional Compilation Example
#If Vba7 Then
     ' Code is running in  32-bit or 64-bit VBA7.
     #If Win64 Then
          ' Code is running in 64-bit VBA7.
     #Else
          ' Code is not running in 64-bit VBA7.
     #End If
#Else
     ' Code is NOT running in 32-bit or 64-bit VBA7.
#End If


DeleteSetting Statement

 Copy code hover
[image]

DeleteSetting Statement
Send feedback

Deletes a section or key setting from an application's entry in the Windows registry or (on the Macintosh) information in the application's initialization file.

Syntax

DeleteSetting appname, section [, key]

The DeleteSetting statement syntax has these named arguments:

Part | Description
appname | Required. String expression containing the name of the application or project to which the section or key setting applies. On the Macintosh, this is the filename of the initialization file in the Preferences folder in the System folder.
section | Required. String expression containing the name of the section where the key setting is being deleted. If only appname and section are provided, the specified section is deleted along with all related key settings.
key | Optional. String expression containing the name of the key setting being deleted.

Remarks

If all arguments are provided, the specified setting is deleted. A run-time error occurs if you attempt to use the DeleteSetting statement on a non-existent section or key setting.

Example

The following example first uses the SaveSetting statement to make entries in the Windows registry (or .ini file on 16-bit Windows platforms) for the application, and then uses the DeleteSetting statement to remove them. Because no key argument is specified, the whole section is deleted, including the section name and all its keys.

Copy code Copy code
' Place some settings in the registry.
SaveSetting appname := "MyApp", section := "Startup", _
 key := "Top", setting := 75
SaveSetting "MyApp","Startup", "Left", 50
' Remove section and all its settings from registry.
DeleteSetting "MyApp", "Startup"


Dim Statement

 Copy code hover
[image]

Dim Statement
Send feedback

Declares variables and allocates storage space.

Syntax

Dim [WithEvents] varname[([subscripts])] [As [New] type] [, [WithEvents] varname[([subscripts])] [As [New] type]] . . .

The Dim statement syntax has these parts:

Part | Description
WithEvents | Optional. Keyword that specifies that varname is an object variable used to respond to events triggered by an ActiveX object. WithEvents is valid only in class modules. You can declare as many individual variables as you like using WithEvents, but you can't create arrays with WithEvents. You can't use New with WithEvents.
varname | Required. Name of the variable; follows standard variable naming conventions.
subscripts | Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax: [lower To] upper [, [lower To] upper] . . . When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
New | Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don't have to use the Set statement to assign the object reference. The New keyword can't be used to declare variables of any intrinsic data type, can't be used to declare instances of dependent objects, and can't be used with WithEvents.
type | Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable you declare.

Remarks

Variables declared with Dim at the module level are available to all procedures within the module. At the procedure level, variables are available only within the procedure.

Use the Dim statement at module or procedure level to declare the data type of a variable. For example, the following statement declares a variable as an Integer.

Copy code Copy code
Dim NumberOfEmployees As Integer

Also use a Dim statement to declare the object type of a variable. The following declares a variable for a new instance of a worksheet.

Copy code Copy code
Dim X As New Worksheet

If the New keyword is not used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object.

You can also use the Dim statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

If you don't specify a data type or object type, and there is no Def type statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

Note Note

When you use the Dim statement in a procedure, you generally put the Dim statement at the beginning of the procedure.

Example

This example shows the Dim statement used to declare variables. It also shows the Dim statement used to declare arrays. The default lower bound for array subscripts is 0 and can be overridden at the module level using the Option Base statement.

Copy code Copy code
' AnyValue and MyValue are declared as Variant by default with values
' set to Empty.
Dim AnyValue, MyValue

' Explicitly declare a variable of type Integer.
Dim Number As Integer

' Multiple declarations on a single line. AnotherVar is of type Variant
' because its type is omitted.
Dim AnotherVar, Choice As Boolean, BirthDate As Date

' DayArray is an array of Variants with 51 elements indexed, from
' 0 thru 50, assuming Option Base is set to 0 (default) for
' the current module.
Dim DayArray(50)

' Matrix is a two-dimensional array of integers.
Dim Matrix(3, 4) As Integer

' MyMatrix is a three-dimensional array of doubles with explicit
' bounds.
Dim MyMatrix(1 To 5, 4 To 9, 3 To 5) As Double

' BirthDay is an array of dates with indexes from 1 to 10.
Dim BirthDay(1 To 10) As Date

' MyArray is a dynamic array of variants.
Dim MyArray()


Do...Loop Statement

 Copy code hover
[image]

Do...Loop Statement
Send feedback

Repeats a block of statements while a condition is True or until a condition becomes True.

Syntax

Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]

Loop

Or, you can use this syntax:

Do
[statements]
[Exit Do]
[statements]

Loop [{While | Until} condition]

The Do Loop statement syntax has these parts:

Part | Description
condition | Optional. Numeric expression or string expression that is True or False. If condition is Null, condition is treated as False.
statements | One or more statements that are repeated while, or until, condition is True.

Remarks

Any number of Exit Do statements may be placed anywhere in the Do…Loop as an alternate way to exit a Do…Loop. Exit Do is often used after evaluating some condition, for example, If…Then, in which case the Exit Do statement transfers control to the statement immediately following the Loop.

When used within nested Do…Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where Exit Do occurs.

Example

This example shows how Do...Loop statements can be used. The inner Do...Loop statement loops 10 times, sets the value of the flag to False, and exits prematurely using the Exit Do statement. The outer loop exits immediately upon checking the value of the flag.

Copy code Copy code
Dim Check, Counter
Check = True: Counter = 0 ' Initialize variables.
Do ' Outer loop.
 Do While Counter < 20 ' Inner loop.
 Counter = Counter + 1 ' Increment Counter.
 If Counter = 10 Then ' If condition is True.
 Check = False ' Set value of flag to False.
 Exit Do ' Exit inner loop.
 End If
 LoopLoop Until Check = False ' Exit outer loop immediately.


End Statement

 Copy code hover
[image]

End Statement
Send feedback

Ends a procedure or block.

Syntax

End

End Function

End If

End Property

End Select

End Sub

End Type

End With

The End statement syntax has these forms:

Statement | Description
End | Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement and to clear variables.
End Function | Required to end a Function statement.
End If | Required to end a block If…Then…Else statement.
End Property | Required to end a Property Let, Property Get, or Property Set procedure.
End Select | Required to end a Select Case statement.
End Sub | Required to end a Sub statement.
End Type | Required to end a user-defined type definition (Type statement).
End With | Required to end a With statement.

Remarks

When executed, the End statement resets all module-level variables and all static local variables in all modules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note Note

The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events of forms and class modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

The End statement provides a way to force your program to halt. For normal termination of a Visual Basic program, you should unload all forms. Your program closes as soon as there are no other programs holding references to objects created from your public class modules and no code executing.

Example

This example uses the End Statement to end code execution if the user enters an invalid password.

Copy code Copy code
Sub Form_Load
 Dim Password, Pword
 PassWord = "Swordfish"
 Pword = InputBox("Type in your password")
 If Pword <> PassWord Then
 MsgBox "Sorry, incorrect password"
 EndEnd IfEnd Sub


Enum Statement

 Copy code hover
[image]

Enum Statement
Send feedback

Declares a type for an enumeration.

Syntax

[Public | Private] Enum name

membername [= constantexpression]

membername [= constantexpression]

. . .

End Enum

The Enum statement has these parts:

Part | Description
Public | Optional. Specifies that the Enum type is visible throughout the project. Enum types are Public by default.
Private | Optional. Specifies that the Enum type is visible only within the module in which it appears.
name | Required. The name of the Enum type. The name must be a valid Visual Basic identifier and is specified as the type when declaring variables or parameters of the Enum type.
membername | Required. A valid Visual Basic identifier specifying the name by which a constituent element of the Enum type will be known.
constantexpression | Optional. Value of the element (evaluates to a Long). If no constantexpression is specified, the value assigned is either zero (if it is the first membername), or 1 greater than the value of the immediately preceding membername.

Remarks

Enumeration variables are variables declared with an Enum type. Both variables and parameters can be declared with an Enum type. The elements of the Enum type are initialized to constant values within the Enum statement. The assigned values can't be modified at run time and can include both positive and negative numbers. For example:

Copy code Copy code
Enum SecurityLevel
 IllegalEntry = -1
 SecurityLevel1 = 0
 SecurityLevel2 = 1
End Enum

An Enum statement can appear only at module level. Once the Enum type is defined, it can be used to declare variables, parameters, or procedures returning its type. You can't qualify an Enum type name with a module name. Public Enum types in a class module are not members of the class; however, they are written to the type library. Enum types defined in standard modules aren't written to type libraries. Public Enum types of the same name can't be defined in both standard modules and class modules, since they share the same name space. When two Enum types in different type libraries have the same name, but different elements, a reference to a variable of the type depends on which type library has higher priority in the References.

You can't use an Enum type as the target in a With block.

Example

The following example shows the Enum statement used to define a collection of named constants. In this case, the constants are colors you might choose to design data entry forms for a database.

Copy code Copy code
Public Enum InterfaceColors
 icMistyRose = &HE1E4FF&
 icSlateGray = &H908070&
 icDodgerBlue = &HFF901E&
 icDeepSkyBlue = &HFFBF00&
 icSpringGreen = &H7FFF00&
 icForestGreen = &H228B22&
 icGoldenrod = &H20A5DA&
 icFirebrick = &H2222B2&
End Enum


Erase Statement

 Copy code hover
[image]

Erase Statement
Send feedback

Reinitializes the elements of fixed-size arrays and releases dynamic-array storage space.

Syntax

Erase arraylist

The required arraylist argument is one or more comma-delimited array variables to be erased.

Remarks

Erase behaves differently depending on whether an array is fixed-size (ordinary) or dynamic. Erase recovers no memory for fixed-size arrays. Erase sets the elements of a fixed array as follows:

Type of Array | Effect of Erase on Fixed-Array Elements
Fixed numeric array | Sets each element to zero.
Fixed string array (variable length) | Sets each element to a zero-length string ("").
Fixed string array (fixed length) | Sets each element to zero.
Fixed Variant array | Sets each element to Empty.
Array of user-defined types | Sets each element as if it were a separate variable.
Array of objects | Sets each element to the special value Nothing.

Erase frees the memory used by dynamic arrays. Before your program can refer to the dynamic array again, it must redeclare the array variable's dimensions using a ReDim statement.

Example

This example uses the Erase statement to reinitialize the elements of fixed-size arrays and deallocate dynamic-array storage space.

Copy code Copy code
' Declare array variables.
Dim NumArray(10) As Integer ' Integer array.
Dim StrVarArray(10) As String ' Variable-string array.
Dim StrFixArray(10) As String * 10 ' Fixed-string array.
Dim VarArray(10) As Variant ' Variant array.
Dim DynamicArray() As Integer ' Dynamic array.
ReDim DynamicArray(10) ' Allocate storage space.
Erase NumArray ' Each element set to 0.
Erase StrVarArray ' Each element set to zero-length
 ' string ("").
Erase StrFixArray ' Each element set to 0.
Erase VarArray ' Each element set to Empty.
Erase DynamicArray ' Free memory used by array.


Error Statement

 Copy code hover
[image]

Error Statement
Send feedback

Simulates the occurrence of an error.

Syntax

Error errornumber

The required errornumber can be any valid error number.

Remarks

The Error statement is supported for backward compatibility. In new code, especially when creating objects, use the Err object's Raise method to generate run-time errors.

If errornumber is defined, the Error statement calls the error handler after the properties of Err object are assigned the following default values:

Property | Value
Number | Value specified as argument to Error statement. Can be any valid error number.
Source | Name of the current Visual Basic project.
Description | String expression corresponding to the return value of the Error function for the specified Number, if this string exists. If the string doesn't exist, Description contains a zero-length string ("").
HelpFile | The fully qualified drive, path, and file name of the appropriate Visual Basic Help file.
HelpContext | The appropriate Visual Basic Help file context ID for the error corresponding to the Number property.
LastDLLError | Zero.

If no error handler exists or if none is enabled, an error message is created and displayed from the Err object properties.

Note Note

Not all Visual Basic host applications can create objects. See your host application's documentation to determine whether it can create classes and objects.

Example

This example uses the Error statement to simulate error number 11.

Copy code Copy code
On Error Resume Next ' Defer error handling.
Error 11 ' Simulate the "Division by zero" error.


Event Statement

 Copy code hover
[image]

Event Statement
Send feedback

Declares a user-defined event.

Syntax

[Public] Event procedurename [(arglist)]

The Event statement has these parts:

Part | Description
Public | Optional. Specifies that the Event visible throughout the project. Events types are Public by default. Note that events can only be raised in the module in which they are declared.
procedurename | Required. Name of the event; follows standard variable naming conventions.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )] [As type]

Part | Description
ByVal | Optional. Indicates that the argument is passed by value.
ByRef | Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.
varname | Required. Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

Once the event has been declared, use the RaiseEvent statement to fire the event. A syntax error occurs if an Event declaration appears in a standard module. An event can't be declared to return a value. A typical event might be declared and raised as shown in the following fragments:

Copy code Copy code
' Declare an event at module level of a class module

Event LogonCompleted (UserName as String)

Sub
 RaiseEvent LogonCompleted("AntoineJan")
End Sub
Note Note

You can declare event arguments just as you do arguments of procedures, with the following exceptions: events cannot have named arguments, Optional arguments, or ParamArray arguments. Events do not have return values.

Example

The following example uses events to count off seconds during a demonstration of the fastest 100 meter race. The code illustrates all of the event-related methods, properties, and statements, including the Event statement.

The class that raises an event is the event source, and the classes that implement the event are the sinks. An event source can have multiple sinks for the events it generates. When the class raises the event, that event is fired on every class that has elected to sink events for that instance of the object.

The example also uses a form (Form1 ) with a button (Command1 ), a label (Label1 ), and two text boxes (Text1 and Text2 ). When you click the button, the first text box displays "From Now" and the second starts to count seconds. When the full time (9.84 seconds) has elapsed, the first text box displays "Until Now" and the second displays "9.84"

The code for specifies the initial and terminal states of the form. It also contains the code executed when events are raised.

Copy code Copy code
Option Explicit

Private WithEvents mText As TimerState

Private Sub Command1_Click()
Text1.Text = "From Now"
 Text1.Refresh
 Text2.Text = "0"
 Text2.Refresh
Call mText.TimerTask(9.84)
End Sub

Private Sub Form_Load()
 Command1.Caption = "Click to Start Timer"
 Text1.Text = ""
 Text2.Text = ""
 Label1.Caption = "The fastest 100 meter run took this long:"
 Set mText = New TimerState
 End Sub

Private Sub mText_ChangeText()
 Text1.Text = "Until Now"
 Text2.Text = "9.84"
End Sub

Private Sub mText_UpdateTime(ByVal dblJump As Double)
 Text2.Text = Str(Format(dblJump, "0"))
 DoEvents
End Sub

The remaining code is in a class module named TimerState. The Event statements declare the procedures initiated when events are raised.

Copy code Copy code
Option Explicit
Public Event UpdateTime(ByVal dblJump As Double)Public Event ChangeText()

Public Sub TimerTask(ByVal Duration As Double)
 Dim dblStart As Double
 Dim dblSecond As Double
 Dim dblSoFar As Double
 dblStart = Timer
 dblSoFar = dblStart

 Do While Timer < dblStart + Duration
 If Timer - dblSoFar >= 1 Then
 dblSoFar = dblSoFar + 1
 RaiseEvent UpdateTime(Timer - dblStart)
 End If
 Loop

 RaiseEvent ChangeText

End Sub


Exit Statement

 Copy code hover
[image]

Exit Statement
Send feedback

Exits a block of Do…Loop, For…Next, Function, Sub, or Property code.

Syntax

Exit Do

Exit For

Exit Function

Exit Property

Exit Sub

The Exit statement syntax has these forms:

Statement | Description
Exit Do | Provides a way to exit a Do...Loop statement. It can be used only inside a Do...Loop statement. Exit Do transfers control to the statement following the Loop statement. When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where Exit Do occurs.
Exit For | Provides a way to exit a For loop. It can be used only in a For...Next or For Each...Next loop. Exit For transfers control to the statement following the Next statement. When used within nested For loops, Exit For transfers control to the loop that is one nested level above the loop where Exit For occurs.
Exit Function | Immediately exits the Function procedure in which it appears. Execution continues with the statement following the statement that called the Function.
Exit Property | Immediately exits the Property procedure in which it appears. Execution continues with the statement following the statement that called the Property procedure.
Exit Sub | Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure.

Remarks

Do not confuse Exit statements with End statements. Exit does not define the end of a structure.

Example

This example uses the Exit statement to exit a For...Next loop, a Do...Loop, and a Sub procedure.

Copy code Copy code
Sub ExitStatementDemo()
Dim I, MyNum
 Do ' Set up infinite loop.
 For I = 1 To 1000 ' Loop 1000 times.
 MyNum = Int(Rnd * 1000) ' Generate random numbers.
 Select Case MyNum ' Evaluate random number.
 Case 7: Exit For ' If 7, exit For...Next.
 Case 29: Exit Do ' If 29, exit Do...Loop.
 Case 54: Exit Sub ' If 54, exit Sub procedure.
 End Select
 Next I
 Loop
End Sub


FileCopy Statement

 Copy code hover
[image]

FileCopy Statement
Send feedback

Copies a file.

Syntax

FileCopy source, destination

The FileCopy statement syntax has these named arguments:

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

Remarks

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

Example

This example uses the FileCopy statement to copy one file to another. For purposes of this example, assume that is a file containing some data.

Copy code Copy code
Dim SourceFile, DestinationFile
SourceFile = "SRCFILE" ' Define source file name.
DestinationFile = "DESTFILE" ' Define target file name.
FileCopy SourceFile, DestinationFile ' Copy source to target.


For Each...Next Statement

 Copy code hover
[image]

For Each...Next Statement
Send feedback

Repeats a group of statements for each element in an array or collection.

Syntax

For Each element In group
[statements]
[Exit For]
[statements]

Next [element]

The For...Each...Next statement syntax has these parts:

Part | Description
element | Required. Variable used to iterate through the elements of the collection or array. For collections, element can only be a Variant variable, a generic object variable, or any specific object variable. For arrays, element can only be a Variant variable.
group | Required. Name of an object collection or array (except an array of user-defined types).
statements | Optional. One or more statements that are executed on each item in group.

Remarks

The For…Each block is entered if there is at least one element in group. Once the loop has been entered, all the statements in the loop are executed for the first element in group. If there are more elements in group, the statements in the loop continue to execute for each element. When there are no more elements in group, the loop is exited and execution continues with the statement following the Next statement.

Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. Exit For is often used after evaluating some condition, for example If…Then, and transfers control to the statement immediately following Next.

You can nest For...Each...Next loops by placing one For…Each…Next loop within another. However, each loop element must be unique.

Note Note

If you omit element in a Next statement, execution continues as if element is included. If a Next statement is encountered before its corresponding For statement, an error occurs.

You can't use the For...Each...Next statement with an array of user-defined types because a Variant can't contain a user-defined type.

Example

This example uses the For Each...Next statement to search the Text property of all elements in a collection for the existence of the string "Hello". In the example, MyObject is a text-related object and is an element of the collection MyCollection. Both are generic names used for illustration purposes only.

Copy code Copy code
Dim Found, MyObject, MyCollection
Found = False    ' Initialize variable.
For Each MyObject In MyCollection    ' Iterate through each element.
    If MyObject.Text = "Hello" Then    ' If Text equals "Hello".
        Found = True    ' Set Found to True.
        Exit For    ' Exit loop.
    End If
Next


For...Next Statement

 Copy code hover
[image]

For...Next Statement
Send feedback

Repeats a group of statements a specified number of times.

Syntax

For counter = start To end [Step step]
[statements]
[Exit For]
[statements]

Next [counter]

The For…Next statement syntax has these parts:

Part | Description
counter | Required. Numeric variable used as a loop counter. The variable can't be a Boolean or an array element.
start | Required. Initial value of counter.
end | Required. Final value of counter.
step | Optional. Amount counter is changed each time through the loop. If not specified, step defaults to one.
statements | Optional. One or more statements between For and Next that are executed the specified number of times.

Remarks

The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:

Value | Loop executes if
Positive or 0 | counter <= end
Negative | counter >= end

After all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement.

Tip Tip

Changing the value of counter while inside a loop can make it more difficult to read and debug your code.

Any number of Exit For statements may be placed anywhere in the loop as an alternate way to exit. Exit For is often used after evaluating of some condition, for example If...Then, and transfers control to the statement immediately following Next.

You can nest For...Next loops by placing one For...Next loop within another. Give each loop a unique variable name as its counter. The following construction is correct:

Copy code Copy code
For I = 1 To 10
 For J = 1 To 10
 For K = 1 To 10
 ...
 Next K
 Next J
Next I
Note Note

If you omit counter in a Next statement, execution continues as if counter is included. If a Next statement is encountered before its corresponding For statement, an error occurs.

Example

This example uses the For...Next statement to create a string that contains 10 instances of the numbers 0 through 9, each string separated from the other by a single space. The outer loop uses a loop counter variable that is decremented each time through the loop.

Copy code Copy code
Dim Words, Chars, MyString
For Words = 10 To 1 Step -1 ' Set up 10 repetitions.
 For Chars = 0 To 9 ' Set up 10 repetitions.
 MyString = MyString & Chars ' Append number to string.
 Next Chars ' Increment counter
 MyString = MyString & " " ' Append a space.
Next Words


Function Statement

 Copy code hover
[image]

Function Statement
Send feedback

Declares the name, arguments, and code that form the body of a Function procedure.

Syntax

[Public | Private | Friend] [Static] Function name [(arglist)] [As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]

End Function

The Function statement syntax has these parts:

Part | Description
Public | Optional. Indicates that the Function procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private, the procedure is not available outside the project.
Private | Optional. Indicates that the Function procedure is accessible only to other procedures in the module where it is declared.
Friend | Optional. Used only in a class module. Indicates that the Function procedure is visible throughout the project, but not visible to a controller of an instance of an object.
Static | Optional. Indicates that the Function procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Function, even if they are used in the procedure.
name | Required. Name of the Function; follows standard variable naming conventions.
arglist | Optional. List of variables representing arguments that are passed to the Function procedure when it is called. Multiple variables are separated by commas.
type | Optional. Data type of the value returned by the Function procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String, or (except fixed length), Object, Variant, or any user-defined type.
statements | Optional. Any group of statements to be executed within the Function procedure.
expression | Optional. Return value of the Function.

The arglist argument has the following syntax and parts:

[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]

Part | Description
Optional | Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used.
ByVal | Optional. Indicates that the argument is passed by value.
ByRef | Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.
ParamArray | Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.
varname | Required. Name of the variable representing the argument; follows standard variable naming conventions.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported) Date, String (variable length only), Object, Variant, or a specific object type. If the parameter is not Optional, a user-defined type may also be specified.
defaultvalue | Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

Remarks

If not explicitly specified using Public, Private, or Friend, Function procedures are public by default. If Static isn't used, the value of local variables is not preserved between calls. The Friend keyword can only be used in class modules. However, Friend procedures can be accessed by procedures in any module of a project. A Friend procedure does't appear in the type library of its parent class, nor can a Friend procedure be late bound.

Function procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword usually isn't used with recursive Function procedures.

All executable code must be in procedures. You can't define a Function procedure inside another Function, Sub, or Property procedure.

The Exit Function statement causes an immediate exit from a Function procedure. Program execution continues with the statement following the statement that called the Function procedure. Any number of Exit Function statements can appear anywhere in a Function procedure.

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub procedure, you can use a Function procedure on the right side of an expression in the same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the value returned by the function.

You call a Function procedure using the function name, followed by the argument list in parentheses, in an expression. See the Call statement for specific information on how to call Function procedures.

To return a value from a function, assign the value to the function name. Any number of such assignments can appear anywhere within the procedure. If no value is assigned to name, the procedure returns a default value: a numeric function returns 0, a string function returns a zero-length string (""), and a Variant function returns Empty. A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the Function.

The following example shows how to assign a return value to a function named . In this case, False is assigned to the name to indicate that some value was not found.

Copy code Copy code
Function BinarySearch(. . .) As Boolean
. . .
 ' Value not found. Return a value of False.
 If lower > upper Then
 BinarySearch = False
 Exit Function
 End If
. . .
End Function

Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant, or variable, it is assumed that your procedure refers 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.

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.

Example

This example uses the Function statement to declare the name, arguments, and code that form the body of a Function procedure. The last example uses hard-typed, initialized Optional arguments.

Copy code Copy code
' The following user-defined function returns the square root of the
' argument passed to it.
Function CalculateSquareRoot(NumberArg As Double) As Double
 If NumberArg < 0 Then ' Evaluate argument.
 Exit Function ' Exit to calling procedure.
 Else
 CalculateSquareRoot = Sqr(NumberArg) ' Return square root.
 End If
End Function

Using the ParamArray keyword enables a function to accept a variable number of arguments. In the following definition, is passed by value.

Copy code Copy code
                      Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs())
Dim ReturnValue
' If the function is invoked as follows:
ReturnValue = CalcSum(4, 3 ,2 ,1)
' Local variables are assigned the following values: FirstArg = 4,
' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default
' lower bound for arrays = 1.

Optional arguments can have default values and types other than Variant.

Copy code Copy code
' If a function's arguments are defined as follows:
Function MyFunc(MyStr As String, Optional MyArg1 As _ Integer = 5, Optional MyArg2 = "Dolly")
Dim RetVal
' The function can be invoked as follows:
RetVal = MyFunc("Hello", 2, "World") ' All 3 arguments supplied.
RetVal = MyFunc("Test", , 5) ' Second argument omitted.
' Arguments one and three using named-arguments.
RetVal = MyFunc(MyStr:="Hello ", MyArg1:=7)


Get Statement

 Copy code hover
[image]

Get Statement
Send feedback

Reads data from an open disk file into a variable.

Syntax

Get [#]filenumber, [recnumber], varname

The Get statement syntax has these parts:

Part | Description
filenumber | Required. Any valid file number.
recnumber | Optional. Variant (Long). Record number (Random mode files) or byte number (Binary mode files) at which reading begins.
varname | Required. Valid variable name into which data is read.

Remarks

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

The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit recnumber, the next record or byte following the last Get or Put statement (or pointed to by the last Seek function) is read. You must include delimiting commas, for example:

Copy code Copy code
                      Get #4,,FileBuffer

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

  • If the length of the data being read is less than the length specified in the Len clause of the Open statement, Get reads subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being read.

  • If the variable being read into is a variable-length string, Get reads a 2-byte descriptor containing the string length and then reads the data that goes into the variable. Therefore, the record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.

  • If the variable being read into is a Variant of numeric type, Get reads 2 bytes identifying the VarType of the Variant and then the data that goes into the variable. For example, when reading a Variant of VarType 3, Get reads 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.

    Note Note

    You can use the Get statement to read a Variant array from disk, but you can't use Get to read a scalar Variant containing an array. You also can't use Get to read objects from disk.

  • If the variable being read into is a Variant of VarType 8 (String), Get reads 2 bytes identifying the VarType, 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 a dynamic array, Get reads a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to read the array data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written to disk.

    Copy code Copy code
    Dim MyArray(1 To 5,1 To 10) As Integer

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

  • If the variable being read into is a fixed-size array, Get reads only the data. No descriptor is read.

  • If the variable being read into is any other type of variable (not a variable-length string or a Variant), Get reads only the variable data. The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being read.

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

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

  • The Len clause in the Open statement has no effect. Get reads all variables from disk contiguously; that is, with no padding between records.

  • For any array other than an array in a user-defined type, Get reads only the data. No descriptor is read.

  • Get reads variable-length strings that aren't elements of user-defined types without expecting the 2-byte length descriptor. The number of bytes read equals the number of characters already in the string. For example, the following statements read 10 bytes from file number 1:

    Copy code Copy code
    VarString = String(10," ")
Get #1,,VarString

Example

This example uses the Get statement to read data from a file into a variable. This example assumes that TESTFILE is a file containing five records of the user-defined type is a file containing five records of the user-defined type Record .

Copy code Copy code
Type Record ' Define user-defined type.
 ID As Integer
 Name As String * 20
End Type

Dim MyRecord As Record, Position ' Declare variables.
' Open sample file for random access.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
' Read the sample file using the Get statement.
Position = 3 ' Define record number.
Get #1, Position, MyRecord ' Read third record.
Close #1 ' Close file.


GoSub...Return Statement

 Copy code hover
[image]

GoSub...Return Statement
Send feedback

Branches to and returns from a subroutine within a procedure.

Syntax

GoSub line
...
line

line
...

Return

The line argument can be any line label or line number.

Remarks

You can use GoSub and Return anywhere in a procedure, but GoSub and the corresponding Return statement must be in the same procedure. A subroutine can contain more than one Return statement, but the first Return statement encountered causes the flow of execution to branch back to the statement immediately following the most recently executed GoSub statement.

Note Note

You can't enter or exit Sub procedures with GoSub...Return.
Tip Tip

Creating separate procedures that you can call may provide a more structured alternative to using GoSub...Return.

Example

This example uses GoSub to call a subroutine within a Sub procedure. The Return statement causes the execution to resume at the statement immediately following the GoSub statement. The Exit Sub statement is used to prevent control from accidentally flowing into the subroutine.

Copy code Copy code
Sub GosubDemo()
Dim Num
' Solicit a number from the user.
 Num = InputBox("Enter a positive number to be divided by 2.")
' Only use routine if user enters a positive number.
 If Num > 0 Then GoSub MyRoutine
 Debug.Print Num
 Exit Sub ' Use Exit to prevent an error.
MyRoutine:
 Num = Num/2 ' Perform the division.
 Return ' Return control to statement.
End Sub ' following the GoSub statement.


GoTo Statement

 Copy code hover
[image]

GoTo Statement
Send feedback

Branches unconditionally to a specified line within a procedure.

Syntax

GoTo line

The required line argument can be any line label or line number.

Remarks

GoTo can branch only to lines within the procedure where it appears.

Note Note

Too many GoTo statements can make code difficult to read and debug. Use structured control statements (Do...Loop, For...Next, If...Then...Else, Select Case) whenever possible.

Example

This example uses the GoTo statement to branch to line labels within a procedure.

Copy code Copy code
Sub GotoStatementDemo()
Dim Number, MyString
 Number = 1 ' Initialize variable.
 ' Evaluate Number and branch to appropriate label.
 If Number = 1 Then GoTo Line1 Else GoTo Line2

Line1:
 MyString = "Number equals 1"
 GoTo LastLine ' Go to LastLine.
Line2:
 ' The following statement never gets executed.
 MyString = "Number equals 2"
LastLine:
 Debug.Print MyString ' Print "Number equals 1" in
 ' the Immediate window.
End Sub


If...Then...Else Statement

 Copy code hover
[image]

If...Then...Else Statement
Send feedback

Conditionally executes a group of statements, depending on the value of an expression.

Syntax

If condition Then [statements] [Else elsestatements]

Or, you can use the block form syntax:

If condition Then
[statements]

[ElseIf condition-n Then
[elseifstatements]

[Else
[elsestatements]]

End If

The If...Then...Else statement syntax has these parts:

Part | Description
condition | Required. One or more of the following two types of expressions:
 | A numeric expression or string expression that evaluates to True or False. If condition is Null, condition is treated as False.
 | An expression of the form TypeOf objectname Is objecttype. The objectname is any object reference and objecttype is any valid object type. The expression is True if objectname is of the object type specified by objecttype; otherwise it is False.
statements | Optional in block form; required in single-line form that has no Else clause. One or more statements separated by colons; executed if condition is True.
condition-n | Optional. Same as condition.
elseifstatements | Optional. One or more statements executed if associated condition-n is True.
elsestatements | Optional. One or more statements executed if no previous condition or condition-n expression is True.

Remarks

You can use the single-line form (first syntax) for short, simple tests. However, the block form (second syntax) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.

Note Note

With the single-line form, it is possible to have multiple statements executed as the result of an If...Then decision. All statements must be on the same line and separated by colons, as in the following statement:
Copy code Copy code
If A > 10 Then A = A + 1 : B = B + A : C = C + B

A block form If statement must be the first statement on a line. The Else, ElseIf, and End If parts of the statement can have only a line number or line label preceding them. The block If must end with an End If statement.

To determine whether or not a statement is a block If, examine what follows the Then keyword. If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement.

The Else and ElseIf clauses are both optional. You can have as many ElseIf clauses as you want in a block If, but none can appear after an Else clause. Block If statements can be nested; that is, contained within one another.

When executing a block If (second syntax), condition is tested. If condition is True, the statements following Then are executed. If condition is False, each ElseIf condition (if any) is evaluated in turn. When a True condition is found, the statements immediately following the associated Then are executed. If none of the ElseIf conditions are True (or if there are no ElseIf clauses), the statements following Else are executed. After executing the statements following Then or Else, execution continues with the statement following End If.

Tip Select Case may be more useful when evaluating a single expression that has several possible actions. However, the TypeOf objectname Is objecttype clause can't be used with the Select Case statement.

Note Note

TypeOf cannot be used with hard data types such as Long, Integer, and so forth other than Object.

Example

This example shows both the block and single-line forms of the If...Then...Else statement. It also illustrates the use of If TypeOf...Then...Else.

Copy code Copy code
Dim Number, Digits, MyString
Number = 53 ' Initialize variable.
If Number < 10 Then
 Digits = 1
ElseIf Number < 100 Then
' Condition evaluates to True so the next statement is executed.
 Digits = 2
Else
 Digits = 3
End If

' Assign a value using the single-line form of syntax.
If Digits = 1 Then MyString = "One" Else MyString = "More than one"

Use If TypeOf construct to determine whether the Control passed into a procedure is a text box.

Copy code Copy code
Sub ControlProcessor(MyControl As Control)
 If TypeOf MyControl Is CommandButton Then
 Debug.Print "You passed in a " & TypeName(MyControl)
 ElseIf TypeOf MyControl Is CheckBox Then
 Debug.Print "You passed in a " & TypeName(MyControl)
 ElseIf TypeOf MyControl Is TextBox Then
 Debug.Print "You passed in a " & TypeName(MyControl)
 End If
End Sub


Implements Statement

 Copy code hover
[image]

Implements Statement
Send feedback

Specifies an interface or class that will be implemented in the class module in which it appears.

Syntax

Implements [InterfaceName | Class]

The required InterfaceName or Class is the name of an interface or class in a type library whose methods will be implemented by the corresponding methods in the Visual Basic class.

Remarks

An interface is a collection of prototypes representing the members (methods and properties) the interface encapsulates; that is, it contains only the declarations for the member procedures. A class provides an implementation of all of the methods and properties of one or more interfaces. Classes provide the code used when each function is called by a controller of the class. All classes implement at least one interface, which is considered the default interface of the class. In Visual Basic, any member that isn't explicitly a member of an implemented interface is implicitly a member of the default interface.

When a Visual Basic class implements an interface, the Visual Basic class provides its own versions of all the Public procedures specified in the type library of the Interface. In addition to providing a mapping between the interface prototypes and your procedures, the Implements statement causes the class to accept COM QueryInterface calls for the specified interface ID.

Note Note

Visual Basic does not implement derived classes or interfaces.

When you implement an interface or class, you must include all the Public procedures involved. A missing member in an implementation of an interface or class causes an error. If you don't place code in one of the procedures in a class you are implementing, you can raise the appropriate error (Const E_NOTIMPL = &H80004001) so a user of the implementation understands that a member is not implemented.

The Implements statement can't appear in a standard module.

Example

The following example shows how to use the Implements statement to make a set of declarations available to multiple classes. By sharing the declarations through the Implements statement, neither class has to make any declarations itself.

Assume there are two forms. The Selector form has two buttons, Customer Data and Supplier Data. To enter name and address information for a customer or a supplier, the user clicks the Customer button or the Supplier button on the Selector form, and then enters the name and address using the Data Entry form. The Data Entry form has two text fields, Name and Address.

The following code for the shared declarations is in a class called PersonalData:

Copy code Copy code
Public Name As String
Public Address As String

The code supporting the customer data is in a class module called Customer:

Copy code Copy code
                      Implements PersonalData
Private Property Get PersonalData_Address() As String
PersonalData_Address = "CustomerAddress"
End Property

Private Property Let PersonalData_Address(ByVal RHS As String)
'
End Property

Private Property Let PersonalData_Name(ByVal RHS As String)
'
End Property

Private Property Get PersonalData_Name() As String
PersonalData_Name = "CustomerName"
End Property

The code supporting the supplier data is in a class module called Supplier:

Copy code Copy code
                      Implements PersonalData

Private Property Get PersonalData_Address() As String
PersonalData_Address = "SupplierAddress"
End Property

Private Property Let PersonalData_Address(ByVal RHS As String)
'
End Property

Private Property Let PersonalData_Name(ByVal RHS As String)
'
End Property

Private Property Get PersonalData_Name() As String
PersonalData_Name = "SupplierName"
End Property

The following code supports the Selector form:

Copy code Copy code
Private cust As New Customer
Private sup As New Supplier

Private Sub Command1_Click()
Dim frm2 As New Form2
 Set frm2.PD = cust
 frm2.Show 1
End Sub

Private Sub Command2_Click()
Dim frm2 As New Form2
 Set frm2.PD = sup
 frm2.Show 1
End Sub

The following code supports the Data Entry form:

Copy code Copy code
Private m_pd As PersonalData
Private Sub Form_Load()
 With m_pd
 Text1 = .Name
 Text2 = .Address
 End With
End Sub
Public Property Set PD(Data As PersonalData)
 Set m_pd = Data
End Property


Input # Statement

 Copy code hover
[image]

Input # Statement
Send feedback

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

Syntax

Input # filenumber, varlist

The Input # statement syntax has these parts:

Part | Description
filenumber | Required. Any valid file number.
varlist | Required. Comma-delimited list of variables that are assigned values read from the file — can't be an array or object variable. However, variables that describe an element of an array or user-defined type may be used.

Remarks

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

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

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

Double quotation marks () within input data are ignored.

Note Note

You should not write strings that contain embedded quotation marks, for example, "1,2""X" for use with the Input # statement: Input # parses this string as two complete and separate strings.

Data items in a file must appear in the same order as the variables in varlist and match variables of the same data type. If a variable is numeric and the data is not numeric, a value of zero is assigned to the variable.

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

Note Note

To be able to correctly read data from a file into variables using Input #, use the Write # statement instead of the Print # statement to write the data to the files. Using Write # ensures each separate data field is properly delimited.

Example

This example uses the Input # statement to read data from a file into two variables. This example assumes that is a file with a few lines of data written to it using the Write # statement; that is, each line contains a string in quotations and a number separated by a comma, for example, ("Hello", 234).

Copy code Copy code
Dim MyString, MyNumber
Open "TESTFILE" For Input As #1    ' Open file for input.
Do While Not EOF(1)    ' Loop until end of file.
    Input #1, MyString, MyNumber    ' Read data into two variables.
    Debug.Print MyString, MyNumber    ' Print data to the Immediate window.
Loop
Close #1    ' Close file.


Kill Statement

 Copy code hover
[image]

Kill Statement
Send feedback

Deletes files from a disk.

Syntax

Kill pathname

The required pathname argument is a string expression that specifies one or more file names to be deleted. The pathname may include the directory or folder, and the drive.

Remarks

In Microsoft Windows, Kill supports the use of multiple-character (*) and single-character (?) wildcards to specify multiple files. However, on the Macintosh, these characters are treated as valid file name characters and can't be used as wildcards to specify multiple files.

Since the Macintosh doesn't support the wildcards, use the file type to identify groups of files to delete. You can use the MacID function to specify file type instead of repeating the command with separate file names. For example, the following statement deletes all TEXT files in the current folder.

Copy code Copy code
Kill MacID("TEXT")

If you use the MacID function with Kill in Microsoft Windows, an error occurs.

An error occurs if you try to use Kill to delete an open file.

Note Note

To delete directories, use the RmDir statement.

Example

This example uses the Kill statement to delete a file from a disk.

Copy code Copy code
' Assume TESTFILE is a file containing some data.
Kill "TestFile" ' Delete file.

' Delete all *.TXT files in current directory.
Kill "*.TXT"


Let Statement

 Copy code hover
[image]

Let Statement
Send feedback

Assigns the value of an expression to a variable or property.

Syntax

[Let] varname = expression

The Let statement syntax has these parts:

Part | Description
Let | Optional. Explicit use of the Let keyword is a matter of style, but it is usually omitted.
varname | Required. Name of the variable or property; follows standard variable naming conventions.
expression | Required. Value assigned to the variable or property.

Remarks

A value expression can be assigned to a variable or property only if it is of a data type that is compatible with the variable. You can't assign string expressions to numeric variables, and you can't assign numeric expressions to string variables. If you do, an error occurs at compile time.

Variant variables can be assigned either string or numeric expressions. However, the reverse is not always true. Any Variant except a Null can be assigned to a string variable, but only a Variant whose value can be interpreted as a number can be assigned to a numeric variable. Use the IsNumeric function to determine if the Variant can be converted to a number.

Assigning an expression of one numeric type to a variable of a different numeric type coerces the value of the expression into the numeric type of the resulting variable.

Let statements can be used to assign one record variable to another only when both variables are of the same user-defined type. Use the LSet statement to assign record variables of different user-defined types. Use the Set statement to assign object references to variables.

Example

This example assigns the values of expressions to variables using the explicit Let statement.

Copy code Copy code
Dim MyStr, MyInt
' The following variable assignments use the Let statement.
Let MyStr = "Hello World"
Let MyInt = 5

The following are the same assignments without the Let statement.

Copy code Copy code
Dim MyStr, MyInt
MyStr = "Hello World"
MyInt = 5


Line Input # Statement

 Copy code hover
[image]

Line Input # Statement
Send feedback

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

Syntax

Line Input # filenumber, varname

The Line Input # statement syntax has these parts:

Part | Description
filenumber | Required. Any valid file number.
varname | Required. Valid Variant or String variable name.

Remarks

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

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

Example

This example uses the Line Input # statement to read a line from a sequential file and assign it to a variable. This example assumes that is a text file with a few lines of sample data.

Copy code Copy code
Dim TextLine
Open "TESTFILE" For Input As #1 ' Open file.
Do While Not EOF(1) ' Loop until end of file.
 Line Input #1, TextLine ' Read line into variable.
 Debug.Print TextLine ' Print to the Immediate window.
Loop
Close #1 ' Close file.


Load Statement

 Copy code hover
[image]

Load Statement
Send feedback

Loads an object but doesn't show it.

Syntax

Load object

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

Remarks

When an object is loaded, it is placed in memory, but isn't visible. Use the Show method to make the object visible. Until an object is visible, a user can't interact with it. The object can be manipulated programmatically in its Initialize event procedure.

Example

In the following example, UserForm2 is loaded during UserForm1's Initialize event. Subsequent clicking on UserForm2 reveals UserForm1.

Copy code Copy code
' This is the Initialize event procedure for UserForm1
Private Sub UserForm_Initialize()
 Load UserForm2
 UserForm2.Show
End Sub
' This is the Click event of UserForm2
Private Sub UserForm_Click()
 UserForm2.Hide
End Sub

' This is the click event for UserForm1
Private Sub UserForm_Click()
 UserForm2.Show
End Sub


Lock, Unlock Statements

 Copy code hover
[image]

Lock, Unlock Statements
Send feedback

Controls access by other processes to all or part of a file opened using the Open statement.

Syntax

Lock [#]filenumber[, recordrange]
. . .

Unlock [#]filenumber[, recordrange]

The Lock and Unlock statement syntax has these parts:

Part | Description
filenumber | Required. Any valid file number.
recordrange | Optional. The range of records to lock or unlock.

Settings

The recordrange argument settings are:

recnumber | [start] To end

Setting | Description
recnumber | Record number (Random mode files) or byte number (Binary mode files) at which locking or unlocking begins.
start | Number of the first record or byte to lock or unlock.
end | Number of the last record or byte to lock or unlock.

Remarks

The Lock and Unlock statements are used in environments where several processes might need access to the same file.

Lock and Unlock statements are always used in pairs. The arguments to Lock and Unlock must match exactly.

The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you specify just one record, then only that record is locked or unlocked. If you specify a range of records and omit a starting record (start), all records from the first record to the end of the range (end) are locked or unlocked. Using Lock without recnumber locks the entire file; using Unlock without recnumber unlocks the entire file.

If the file has been opened for sequential input or output, Lock and Unlock affect the entire file, regardless of the range specified by start and end.

Important note Important

Be sure to remove all locks with an Unlock statement before closing a file or quitting your program. Failure to remove locks produces unpredictable results.

Example

This example illustrates the use of the Lock and Unlock statements. While a record is being modified, access by other processes to the record is denied. This example assumes that TESTFILE is a file containing five records of the user-defined type is a file containing five records of the user-defined type Record .

Copy code Copy code
Type Record    ' Define user-defined type.
    ID As Integer
    Name As String * 20
End Type

Dim MyRecord As Record, RecordNumber    ' Declare variables.
' Open sample file for random access.
Open "TESTFILE" For Random Shared As #1 Len = Len(MyRecord)
RecordNumber = 4    ' Define record number.
Lock #1, RecordNumber    ' Lock record.
Get #1, RecordNumber, MyRecord    ' Read record.
MyRecord.ID = 234    ' Modify record.
MyRecord.Name = "John Smith"
Put #1, RecordNumber, MyRecord    ' Write modified record.
Unlock #1, RecordNumber    ' Unlock current record.
Close #1    ' Close file.


LSet Statement

 Copy code hover
[image]

LSet Statement
Send feedback

Left aligns a string within a string variable, or copies a variable of one user-defined type to another variable of a different user-defined type.

Syntax

LSet stringvar = string

LSet varname1 = varname2

The LSet statement syntax has these parts:

Part | Description
stringvar | Required. Name of string variable.
string | Required. String expression to be left-aligned within stringvar.
varname1 | Required. Variable name of the user-defined type being copied to.
varname2 | Required. Variable name of the user-defined type being copied from.

Remarks

LSet replaces any leftover characters in stringvar with spaces.

If string is longer than stringvar, LSet places only the leftmost characters, up to the length of the stringvar, in stringvar.

Using LSet to copy a variable of one user-defined type into a variable of a different user-defined type is not recommended. Copying data of one data type into space reserved for a different data type can cause unpredictable results.

When you copy a variable from one user-defined type to another, the binary data from one variable is copied into the memory space of the other, without regard for the data types specified for the elements.

Example

This example uses the LSet statement to left align a string within a string variable. Although LSet can also be used to copy a variable of one user-defined type to another variable of a different, but compatible, user-defined type, this practice is not recommended. Due to the varying implementations of data structures among platforms, such a use of LSet can't be guaranteed to be portable.

Copy code Copy code
Dim MyString
MyString = "0123456789" ' Initialize string.
Lset MyString = "<-Left" ' MyString contains "<-Left ".


Mid Statement

 Copy code hover
[image]

Mid Statement
Send feedback

Replaces a specified number of characters in a Variant (String) variable with characters from another string.

Syntax

Mid(stringvar, start[, length]) = string

The Mid statement syntax has these parts:

Part | Description
stringvar | Required. Name of string variable to modify.
start | Required; Variant (Long). Character position in stringvar where the replacement of text begins.
length | Optional; Variant (Long). Number of characters to replace. If omitted, all of string is used.
string | Required. String expression that replaces part of stringvar.

Remarks

The number of characters replaced is always less than or equal to the number of characters in stringvar.

Note Note

Use the MidB statement with byte data contained in a string. In the MidB statement, start specifies the byte position within stringvar where replacement begins and length specifies the numbers of bytes to replace.

Example

This example uses the Mid statement to replace a specified number of characters in a string variable with characters from another string.

Copy code Copy code
Dim MyString
MyString = "The dog jumps" ' Initialize string.
Mid(MyString, 5, 3) = "fox" ' MyString = "The fox jumps".
Mid(MyString, 5) = "cow" ' MyString = "The cow jumps".
Mid(MyString, 5) = "cow jumped over" ' MyString = "The cow jumpe".
Mid(MyString, 5, 3) = "duck" ' MyString = "The duc jumpe".


MkDir Statement

 Copy code hover
[image]

MkDir Statement
Send feedback

Creates a new directory or folder.

Syntax

MkDir path

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

Example

This example uses the MkDir statement to create a directory or folder. If the drive is not specified, the new directory or folder is created on the current drive.

Copy code Copy code
                      MkDir "MYDIR" ' Make new directory or folder.


Name Statement

 Copy code hover
[image]

Name Statement
Send feedback

Renames a disk file, directory, or folder.

Syntax

Name oldpathname As newpathname

The Name statement syntax has these parts:

Part | Description
oldpathname | Required. String expression that specifies the existing file name and location — may include directory or folder, and drive.
newpathname | Required. String expression that specifies the new file name and location — may include directory or folder, and drive. The file name specified by newpathname can't already exist.

Remarks

The Name statement renames a file and moves it to a different directory or folder, if necessary. Name can move a file across drives, but it can only rename an existing directory or folder when both newpathname and oldpathname are located on the same drive. Name cannot create a new file, directory, or folder.

Using Name on an open file produces an error. You must close an open file before renaming it. Name arguments cannot include multiple-character (*) and single-character (?) wildcards.

Example

This example uses the Name statement to rename a file. For purposes of this example, assume that the directories or folders that are specified already exist. On the Macintosh, "HD:" is the default drive name and portions of the pathname are separated by colons instead of backslashes.

Copy code Copy code
Dim OldName, NewName
OldName = "OLDFILE": NewName = "NEWFILE" ' Define file names.
Name OldName As NewName ' Rename file.

OldName = "C:\MYDIR\OLDFILE": NewName = "C:\YOURDIR\NEWFILE"
Name OldName As NewName ' Move and rename file.


On Error Statement

 Copy code hover
[image]

On Error Statement
Send feedback

Enables an error-handling routine and specifies the location of the routine within a procedure; can also be used to disable an error-handling routine.

Syntax

On Error GoTo line

On Error Resume Next

On Error GoTo 0

The On Error statement syntax can have any of the following forms:

Statement | Description
On Error GoTo line | Enables the error-handling routine that starts at line specified in the required line argument. The line argument is any line label or line number. If a run-time error occurs, control branches to line, making the error handler active. The specified line must be in the same procedure as the On Error statement; otherwise, a compile-time error occurs.
On Error Resume Next | Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred where execution continues. Use this form rather than On Error GoTo when accessing objects.
On Error GoTo 0 | Disables any enabled error handler in the current procedure.

Remarks

If you don't use an On Error statement, any run-time error that occurs is fatal; that is, an error message is displayed and execution stops.

An "enabled" error handler is one that is turned on by an On Error statement; an "active" error handler is an enabled handler that is in the process of handling an error. If an error occurs while an error handler is active (between the occurrence of the error and a Resume, Exit Sub, Exit Function, or Exit Property statement), the current procedure's error handler can't handle the error. Control returns to the calling procedure. If the calling procedure has an enabled error handler, it is activated to handle the error. If the calling procedure's error handler is also active, control passes back through previous calling procedures until an enabled, but inactive, error handler is found. If no inactive, enabled error handler is found, the error is fatal at the point at which it actually occurred. Each time the error handler passes control back to a calling procedure, that procedure becomes the current procedure. Once an error is handled by an error handler in any procedure, execution resumes in the current procedure at the point designated by the Resume statement.

Note Note

An error-handling routine is not a Sub procedure or Function procedure. It is a section of code marked by a line label or line number.

Error-handling routines rely on the value in the Number property of the Err object to determine the cause of the error. The error-handling routine should test or save relevant property values in the Err object before any other error can occur or before a procedure that might cause an error is called. The property values in the Err object reflect only the most recent error. The error message associated with Err.Number is contained in Err.Description.

On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most recent call out of the procedure containing the On Error Resume Next statement. This statement allows execution to continue despite a run-time error. You can place the error-handling routine where the error would occur, rather than transferring control to another location within the procedure. An On Error Resume Next statement becomes inactive when another procedure is called, so you should execute an On Error Resume Next statement in each called routine if you want inline error handling within that routine.

Note Note

The On Error Resume Next construct may be preferable to On Error GoTo when handling errors generated during access to other objects. Checking Err after each interaction with an object removes ambiguity about which object was accessed by the code. You can be sure which object placed the error code in Err.Number, as well as which object originally generated the error (the object specified in Err.Source).

On Error GoTo 0 disables error handling in the current procedure. It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0. Without an On Error GoTo 0 statement, an error handler is automatically disabled when a procedure is exited.

To prevent error-handling code from running when no error has occurred, place an Exit Sub, Exit Function, or Exit Property statement immediately before the error-handling routine, as in the following fragment:

Copy code Copy code
Sub InitializeMatrix(Var1, Var2, Var3, Var4)
 On Error GoTo ErrorHandler
 . . .
 Exit Sub
ErrorHandler:
 . . .
 Resume Next
End Sub

Here, the error-handling code follows the Exit Sub statement and precedes the End Sub statement to separate it from the procedure flow. Error-handling code can be placed anywhere in a procedure.

Untrapped errors in objects are returned to the controlling application when the object is running as an executable file. Within the development environment, untrapped errors are only returned to the controlling application if the proper options are set. See your host application's documentation for a description of which options should be set during debugging, how to set them, and whether the host can create classes.

If you create an object that accesses other objects, you should try to handle errors passed back from them unhandled. If you cannot handle such errors, map the error code in Err.Number to one of your own errors, and then pass them back to the caller of your object. You should specify your error by adding your error code to the vbObjectError constant. For example, if your error code is 1052, assign it as follows:

Copy code Copy code
Err.Number = vbObjectError + 1052
Note Note

System errors during calls to Windows dynamic-link libraries (DLL) or Macintosh code resources do not raise exceptions and cannot be trapped with Visual Basic error trapping. When calling DLL functions, you should check each return value for success or failure (according to the API specifications), and in the event of a failure, check the value in the Err object's LastDLLError property. LastDLLError always returns zero on the Macintosh.

Example

This example first uses the On Error GoTo statement to specify the location of an error-handling routine within a procedure. In the example, an attempt to delete an open file generates error number 55. The error is handled in the error-handling routine, and control is then returned to the statement that caused the error. The On Error GoTo 0 statement turns off error trapping. Then the On Error Resume Next statement is used to defer error trapping so that the context for the error generated by the next statement can be known for certain. Note that Err.Clear is used to clear the Err object's properties after the error is handled.

Copy code Copy code
Sub OnErrorStatementDemo()
 On Error GoTo ErrorHandler ' Enable error-handling routine.
 Open "TESTFILE" For Output As #1 ' Open file for output.
 Kill "TESTFILE" ' Attempt to delete open
 ' file.
 On Error Goto 0 ' Turn off error trapping.
 On Error Resume Next ' Defer error trapping.
 ObjectRef = GetObject("MyWord.Basic") ' Try to start nonexistent
 ' object, then test for
'Check for likely Automation errors.
 If Err.Number = 440 Or Err.Number = 432 Then
 ' Tell user what happened. Then clear the Err object.
 Msg = "There was an error attempting to open the Automation object!"
 MsgBox Msg, , "Deferred Error Test"
 Err.Clear ' Clear Err object fields
 End If
Exit Sub ' Exit to avoid handler.
ErrorHandler: ' Error-handling routine.
 Select Case Err.Number ' Evaluate error number.
 Case 55 ' "File already open" error.
 Close #1 ' Close open file.
 Case Else
 ' Handle other situations here...
 End Select
 Resume ' Resume execution at same line
 ' that caused the error.
End Sub


On...GoSub, On...GoTo Statements

 Copy code hover
[image]

On...GoSub, On...GoTo Statements
Send feedback

Branch to one of several specified lines, depending on the value of an expression.

Syntax

On expression GoSub destinationlist

On expression GoTo destinationlist

The On...GoSub and On...GoTo statement syntax has these parts:

Part | Description
expression | Required. Any numeric expression that evaluates to a whole number between 0 and 255, inclusive. If expression is any number other than a whole number, it is rounded before it is evaluated.
destinationlist | Required. List of line numbers or line labels separated by commas.

Remarks

The value of expression determines which line is branched to in destinationlist. If the value of expression is less than 1 or greater than the number of items in the list, one of the following results occurs:

If expression is | Then
Equal to 0 | Control drops to the statement following On...GoSub or On...GoTo.
Greater than number of items in list | Control drops to the statement following On...GoSub or On...GoTo.
Negative | An error occurs.
Greater than 255 | An error occurs.

You can mix line numbers and line labels in the same list. You can use as many line labels and line numbers as you like with On...GoSub and On...GoTo. However, if you use more labels or numbers than fit on a single line, you must use the line-continuation character to continue the logical line onto the next physical line.

Tip Tip

Select Case provides a more structured and flexible way to perform multiple branching.

Example

This example uses the On...GoSub and On...GoTo statements to branch to subroutines and line labels, respectively.

Copy code Copy code
Sub OnGosubGotoDemo()
Dim Number, MyString
 Number = 2 ' Initialize variable.
 ' Branch to Sub2.
 On Number GoSub Sub1, Sub2 ' Execution resumes here after
 ' On...GoSub.
 On Number GoTo Line1, Line2 ' Branch to Line2.
 ' Execution does not resume here after On...GoTo.
 Exit Sub
Sub1:
 MyString = "In Sub1" : Return
Sub2:
 MyString = "In Sub2" : Return
Line1:
 MyString = "In Line1"
Line2:
 MyString = "In Line2"
End Sub


Open Statement

 Copy code hover
[image]

Open Statement
Send feedback

Enables input/output (I/O) to a file.

Syntax

Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength]

The Open statement syntax has these parts:

Part | Description
pathname | Required. String expression that specifies a file name — may include directory or folder, and drive.
mode | Required. Keyword specifying the file mode: Append, Binary, Input, Output, or Random. If unspecified, the file is opened for Random access.
access | Optional. Keyword specifying the operations permitted on the open file: Read, Write, or Read Write.
lock | Optional. Keyword specifying the operations restricted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write.
filenumber | Required. A valid file number in the range 1 to 511, inclusive. Use the FreeFile function to obtain the next available file number.
reclength | Optional. Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered.

Remarks

You must open a file before any I/O operation can be performed on it. Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer.

If the file specified by pathname doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes.

If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs.

The Len clause is ignored if mode is Binary.

Important note Important

In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file. In Append and Output modes, you must close a file before opening it with a different file number.

Example

This example illustrates various uses of the Open statement to enable input and output to a file.

The following code opens the file in sequential-input mode.

Copy code Copy code
                      Open "TESTFILE" For Input As #1
' Close before reopening in another mode.
Close #1

This example opens the file in Binary mode for writing operations only.

Copy code Copy code
                      Open "TESTFILE" For Binary Access Write As #1
' Close before reopening in another mode.
Close #1

The following example opens the file in Random mode. The file contains records of the user-defined type .

Copy code Copy code
Type Record ' Define user-defined type.
 ID As Integer
 Name As String * 20
End Type

Dim MyRecord As Record ' Declare variable.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
' Close before reopening in another mode.
Close #1

This code example opens the file for sequential output; any process can read or write to file.

Copy code Copy code
                      Open "TESTFILE" For Output Shared As #1
' Close before reopening in another mode.
Close #1

This code example opens the file in Binary mode for reading; other processes can't read file.

Copy code Copy code
                      Open "TESTFILE" For Binary Access Read Lock Read As #1


Option Base Statement

 Copy code hover
[image]

Option Base Statement
Send feedback

Used at module level to declare the default lower bound for array subscripts.

Syntax

Option Base {0 | 1}

Remarks

Because the default base is 0, the Option Base statement is never required. If used, the statement must appear in a module before any procedures. Option Base can appear only once in a module and must precede array declarations that include dimensions.

Note Note

The To clause in the Dim, Private, Public, ReDim, and Static statements provides a more flexible way to control the range of an array's subscripts. However, if you don't explicitly set the lower bound with a To clause, you can use Option Base to change the default lower bound to 1. The base of an array created with the the ParamArray keyword is zero; Option Base does not affect ParamArray (or the Array function, when qualified with the name of its type library, for example VBA.Array).

The Option Base statement only affects the lower bound of arrays in the module where the statement is located.

Example

This example uses the Option Base statement to override the default base array subscript value of 0. The LBound function returns the smallest available subscript for the indicated dimension of an array. The Option Base statement is used at the module level only.

Copy code Copy code
                      Option base 1 ' Set default array subscripts to 1.

Dim Lower
Dim MyArray(20), TwoDArray(3, 4) ' Declare array variables.
Dim ZeroArray(0 To 5) ' Override default base subscript.
' Use LBound function to test lower bounds of arrays.
Lower = LBound(MyArray) ' Returns 1.
Lower = LBound(TwoDArray, 2) ' Returns 1.
Lower = LBound(ZeroArray) ' Returns 0.


Option Compare Statement

 Copy code hover
[image]

Option Compare Statement
Send feedback

Used at module level to declare the default comparison method to use when string data is compared.

Syntax

Option Compare {Binary | Text | Database}

Remarks

If used, the Option Compare statement must appear in a module before any procedures.

The Option Compare statement specifies the string comparison method (Binary, Text, or Database) for a module. If a module doesn't include an Option Compare statement, the default text comparison method is Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. In Microsoft Windows, sort order is determined by the code page. A typical binary sort order is shown in the following example:

Copy code Copy code
A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive text sort order determined by your system's locale. When the same characters are sorted using Option Compare Text, the following text sort order is produced:

Copy code Copy code
(A=a) < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

Option Compare Database can only be used within Microsoft Access. This results in string comparisons based on the sort order determined by the locale ID of the database where the string comparisons occur.

Example

This example uses the Option Compare statement to set the default string comparison method. The Option Compare statement is used at the module level only.

Copy code Copy code
' Set the string comparison method to Binary.
Option compare Binary ' That is, "AAA" is less than "aaa".
' Set the string comparison method to Text.
Option compare Text ' That is, "AAA" is equal to "aaa".


Option Explicit Statement

 Copy code hover
[image]

Option Explicit Statement
Send feedback

Used at module level to force explicit declaration of all variables in that module.

Syntax

Option Explicit

Remarks

If used, the Option Explicit statement must appear in a module before any procedures.

When Option Explicit appears in a module, you must explicitly declare all variables using the Dim, Private, Public, ReDim, or Static statements. If you attempt to use an undeclared variable name, an error occurs at compile time.

If you don't use the Option Explicit statement, all undeclared variables are of Variant type unless the default type is otherwise specified with a Def type statement.

Note Note

Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear.

Example

This example uses the Option Explicit statement to force explicit declaration of all variables. Attempting to use an undeclared variable causes an error at compile time. The Option Explicit statement is used at the module level only.

Copy code Copy code
                      Option explicit ' Force explicit variable declaration.
Dim MyVar ' Declare variable.
MyInt = 10 ' Undeclared variable generates error.
MyVar = 10 ' Declared variable does not generate error.


Option Private Statement

 Copy code hover
[image]

Option Private Statement
Send feedback

When used in host applications that allow references across multiple projects, Option Private Module prevents a module's contents from being referenced outside its project. In host applications that don't permit such references, for example, standalone versions of Visual Basic, Option Private has no effect.

Syntax

Option Private Module

Remarks

If used, the Option Private statement must appear at module level, before any procedures.

When a module contains Option Private Module, the public parts, for example, variables, objects, and user-defined types declared at module level, are still available within the project containing the module, but they are not available to other applications or projects.

Note Note

Option Private is only useful for host applications that support simultaneous loading of multiple projects and permit references between the loaded projects. For example, Microsoft Excel permits loading of multiple projects and Option Private Module can be used to restrict cross-project visibility. Although Visual Basic permits loading of multiple projects, references between projects are never permitted in Visual Basic.

Example

This example demonstrates the Option Private statement, which is used at module level to indicate that the entire module is private. With Option Private Module, module-level parts not declared Private are available to other modules in the project, but not to other projects or applications.

Copy code Copy code
                      Option private Module ' Indicates that module is private.


Print # Statement

 Copy code hover
[image]

Print # Statement
Send feedback

Writes display-formatted data to a sequential file.

Syntax

Print # filenumber, [outputlist]

The Print # statement syntax has these parts:

Part | Description
filenumber | Required. Any valid file number.
outputlist | Optional. Expression or list of expressions to print.

Settings

The outputlist argument settings are:

[{Spc(n) | Tab[(n)]}] [expression] [charpos]

Setting | Description
Spc( n ) | Used to insert space characters in the output, where n is the number of space characters to insert.
Tab( n ) | Used to position the insertion point to an absolute column number, where n is the column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone.
expression | Numeric expressions or string expressions to print.
charpos | Specifies the insertion point for the next character. Use a semicolon to position the insertion point immediately after the last character displayed. Use Tab(n) to position the insertion point to an absolute column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone. If charpos is omitted, the next character is printed on the next line.

Remarks

Data written with Print # is usually read from a file with Line Input # or Input.

If you omit outputlist and include only a list separator after filenumber, a blank line is printed to the file. Multiple expressions can be separated with either a space or a semicolon. A space has the same effect as a semicolon.

For Boolean data, either True or or False is printed. The True and False keywords are not translated, regardless of the locale.

Date data is written to the file using the standard short date format recognized by your system. When either the date or the time component is missing or zero, only the part provided gets written to the file.

Nothing is written to the file if outputlist data is Empty. However, if outputlist data is Null, Null is written to the file.

For Error data, the output appears as . The Error keyword is not translated regardless of the locale.

All data written to the file using Print # is internationally aware; that is, the data is properly formatted using the appropriate decimal separator.

Because Print # writes an image of the data to the file, you must delimit the data so it prints correctly. If you use Tab with no arguments to move the print position to the next print zone, Print # also writes the spaces between print fields to the file.

Note Note

If, at some future time, you want to read the data from a file using the Input # statement, use the Write # statement instead of the Print # statement to write the data to the file. Using Write # ensures the integrity of each separate data field by properly delimiting it, so it can be read back in using Input #. Using Write # also ensures it can be correctly read in any locale.

Example

This example uses the Print # statement to write data to a file.

Copy code Copy code
Open "TESTFILE" For Output As #1 ' Open file for output.
Print #1, "This is a test" ' Print text to file.
Print #1, ' Print blank line to file.
Print #1, "Zone 1"; Tab ; "Zone 2" ' Print in two print zones.
Print #1, "Hello" ; " " ; "World" ' Separate strings with space.
Print #1, Spc(5) ; "5 leading spaces " ' Print five leading spaces.
Print #1, Tab(10) ; "Hello" ' Print word at column 10.

' Assign Boolean, Date, Null and Error values.
Dim MyBool, MyDate, MyNull, MyError
MyBool = False : MyDate = #February 12, 1969# : MyNull = Null
MyError = CVErr(32767)
' True, False, Null, and Error are translated using locale settings of
' your system. Date literals are written using standard short date
' format.
Print #1, MyBool ; " is a Boolean value"
Print #1, MyDate ; " is a date"
Print #1, MyNull ; " is a null value"
Print #1, MyError ; " is an error value"
Close #1 ' Close file.


Private Statement

 Copy code hover
[image]

Private Statement
Send feedback

Used at module level to declare private variables and allocate storage space.

Syntax

Private [WithEvents] varname[([subscripts])] [As [New] type] [,[WithEvents] varname[([subscripts])] [As [New] type]] . . .

The Private statement syntax has these parts:

Part | Description
WithEvents | Optional. Keyword that specifies that varname is an object variable used to respond to events triggered by an ActiveX object. WithEvents is valid only in class modules. You can declare as many individual variables as you like using WithEvents, but you can't create arrays with WithEvents. You can't use New with WithEvents.
varname | Required. Name of the variable; follows standard variable naming conventions.
subscripts | Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:
 | [lower To] upper [,[lower To] upper] . . .
 | When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
New | Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don't have to use the Set statement to assign the object reference. The New keyword can't be used to declare variables of any intrinsic data type, can't be used to declare instances of dependent objects, and can't be used with WithEvents.
type | Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable being defined.

Remarks

Private variables are available only to the module in which they are declared.

Use the Private statement to declare the data type of a variable. For example, the following statement declares a variable as an Integer:

Copy code Copy code
Private NumberOfEmployees As Integer

You can also use a Private statement to declare the object type of a variable. The following statement declares a variable for a new instance of a worksheet.

Copy code Copy code
Private X As New Worksheet

If the New keyword isn't used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it's assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object.

If you don't specify a data type or object type, and there is no Def type statement in the module, the variable is Variant by default.

You can also use the Private statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

Note Note

When you use the Private statement in a procedure, you generally put the Private statement at the beginning of the procedure.

Example

This example shows the Private statement being used at the module level to declare variables as private; that is, they are available only to the module in which they are declared.

Copy code Copy code
                      Private Number As Integer ' Private Integer variable.
Private NameArray(1 To 5) As String ' Private array variable.
' Multiple declarations, two Variants and one Integer, all Private.
Private MyVar, YourVar, ThisVar As Integer


Property Get Statement

 Copy code hover
[image]

Property Get Statement
Send feedback

Declares the name, arguments, and code that form the body of a Property procedure, which gets the value of a property.

Syntax

[Public | Private | Friend] [Static] Property Get name [(arglist)] [As type]
[statements]
[name = expression]
[Exit Property]
[statements]
[name = expression]

End Property

The Property Get statement syntax has these parts:

Part | Description
Public | Optional. Indicates that the Property Get procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private statement, the procedure is not available outside the project.
Private | Optional. Indicates that the Property Get procedure is accessible only to other procedures in the module where it is declared.
Friend | Optional. Used only in a class module. Indicates that the Property Get procedure is visible throughout the project, but not visible to a controller of an instance of an object.
Static | Optional. Indicates that the Property Get procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Property Get procedure, even if they are used in the procedure.
name | Required. Name of the Property Get procedure; follows standard variable naming conventions, except that the name can be the same as a Property Let or Property Set procedure in the same module.
arglist | Optional. List of variables representing arguments that are passed to the Property Get procedure when it is called. Multiple arguments are separated by commas. The name and data type of each argument in a Property Get procedure must be the same as the corresponding argument in a Property Let procedure (if one exists).
type | Optional. Data type of the value returned by the Property Get procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (except fixed length), Object, Variant, user-defined type, and Arrays. The return type of a Property Get procedure must be the same data type as the last (or sometimes the only) argument in a corresponding Property Let procedure (if one exists) that defines the value assigned to the property on the right side of an expression.
statements | Optional. Any group of statements to be executed within the body of the Property Get procedure.
expression | Optional. Value of the property returned by the procedure defined by the Property Get statement.

The arglist argument has the following syntax and parts:

[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]

Part | Description
Optional | Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword.
ByVal | Optional. Indicates that the argument is passed by value.
ByRef | Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.
ParamArray | Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.
varname | Required. Name of the variable representing the argument; follows standard variable naming conventions.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable length only), Object, Variant, or a specific object type. If the parameter is not Optional, a user-defined type may also be specified.
defaultvalue | Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

Remarks

If not explicitly specified using Public, Private, or Friend, Property procedures are public by default. If Static is not used, the value of local variables is not preserved between calls. The Friend keyword can only be used in class modules. However, Friend procedures can be accessed by procedures in any module of a project. A Friend procedure doesn't appear in the type library of its parent class, nor can a Friend procedure be late bound.

All executable code must be in procedures. You can't define a Property Get procedure inside another Property, Sub, or Function procedure.

The Exit Property statement causes an immediate exit from a Property Get procedure. Program execution continues with the statement following the statement that called the Property Get procedure. Any number of Exit Property statements can appear anywhere in a Property Get procedure.

Like a Sub and Property Let procedure, a Property Get procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub or Property Let procedure, you can use a Property Get procedure on the right side of an expression in the same way you use a Function or a property name when you want to return the value of a property.

Example

This example uses the Property Get statement to define a property procedure that gets the value of a property. The property identifies the current color of a pen as a string.

Copy code Copy code
Dim CurrentColor As Integer
Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3

' Returns the current color of the pen as a string.
Property Get PenColor() As String
 Select Case CurrentColor
 Case RED
 PenColor = "Red"
 Case GREEN
 PenColor = "Green"
 Case BLUE
 PenColor = "Blue"
 End Select
End Property

' The following code gets the color of the pen
' calling the Property Get procedure.
ColorName = PenColor


Property Let Statement

 Copy code hover
[image]

Property Let Statement
Send feedback

Declares the name, arguments, and code that form the body of a Property Let procedure, which assigns a value to a property.

Syntax

[Public | Private | Friend] [Static] Property Let name ([arglist,] value)
[statements]
[Exit Property]
[statements]

End Property

The Property Let statement syntax has these parts:

Part | Description
Public | Optional. Indicates that the Property Let procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private statement, the procedure is not available outside the project.
Private | Optional. Indicates that the Property Let procedure is accessible only to other procedures in the module where it is declared.
Friend | Optional. Used only in a class module. Indicates that the Property Let procedure is visible throughout the project, but not visible to a controller of an instance of an object.
Static | Optional. Indicates that the Property Let procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Property Let procedure, even if they are used in the procedure.
name | Required. Name of the Property Let procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Set procedure in the same module.
arglist | Required. List of variables representing arguments that are passed to the Property Let procedure when it is called. Multiple arguments are separated by commas. The name and data type of each argument in a Property Let procedure must be the same as the corresponding argument in a Property Get procedure.
value | Required. Variable to contain the value to be assigned to the property. When the procedure is called, this argument appears on the right side of the calling expression. The data type of value must be the same as the return type of the corresponding Property Get procedure.
statements | Optional. Any group of statements to be executed within the Property Let procedure.

The arglist argument has the following syntax and parts:

[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]

Part | Description
Optional | Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Note that it is not possible for the right side of a Property Let expression to be Optional.
ByVal | Optional. Indicates that the argument is passed by value.
ByRef | Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.
ParamArray | Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.
varname | Required. Name of the variable representing the argument; follows standard variable naming conventions.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable length only), Object, Variant, or a specific object type. If the parameter is not Optional, a user-defined type may also be specified.
defaultvalue | Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.
Note Note

Every Property Let statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) contains the actual value to be assigned to the property when the procedure defined by the Property Let statement is invoked. That argument is referred to as value in the preceding syntax.

Remarks

If not explicitly specified using Public, Private, or Friend, Property procedures are public by default. If Static isn't used, the value of local variables is not preserved between calls. The Friend keyword can only be used in class modules. However, Friend procedures can be accessed by procedures in any module of a project. A Friend procedure doesn't appear in the type library of its parent class, nor can a Friend procedure be late bound.

All executable code must be in procedures. You can't define a Property Let procedure inside another Property, Sub, or Function procedure.

The Exit Property statement causes an immediate exit from a Property Let procedure. Program execution continues with the statement following the statement that called the Property Let procedure. Any number of Exit Property statements can appear anywhere in a Property Let procedure.

Like a Function and Property Get procedure, a Property Let procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and Property Get procedure, both of which return a value, you can only use a Property Let procedure on the left side of a property assignment expression or Let statement.

Example

This example uses the Property Let statement to define a procedure that assigns a value to a property. The property identifies the pen color for a drawing package.

Copy code Copy code
Dim CurrentColor As Integer
Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3

' Set the pen color property for a Drawing package.
' The module-level variable CurrentColor is set to
' a numeric value that identifies the color used for drawing.
Property Let PenColor(ColorName As String)
 Select Case ColorName ' Check color name string.
 Case "Red"
 CurrentColor = RED ' Assign value for Red.
 Case "Green"
 CurrentColor = GREEN ' Assign value for Green.
 Case "Blue"
 CurrentColor = BLUE ' Assign value for Blue.
 Case Else
 CurrentColor = BLACK ' Assign default value.
 End Select
End Property

' The following code sets the PenColor property for a drawing package
' by calling the Property let procedure.

PenColor = "Red"


Property Set Statement

 Copy code hover
[image]

Property Set Statement
Send feedback

Declares the name, arguments, and code that form the body of a Property procedure, which sets a reference to an object.

Syntax

[Public | Private | Friend] [Static] Property Set name ([arglist,] reference)
[statements]
[Exit Property]
[statements]

End Property

The Property Set statement syntax has these parts:

Part | Description
Optional | Optional. Indicates that the argument may or may not be supplied by the caller.
Public | Optional. Indicates that the Property Set procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private statement, the procedure is not available outside the project.
Private | Optional. Indicates that the Property Set procedure is accessible only to other procedures in the module where it is declared.
Friend | Optional. Used only in a class module. Indicates that the Property Set procedure is visible throughout the project, but not visible to a controller of an instance of an object.
Static | Optional. Indicates that the Property Set procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Property Set procedure, even if they are used in the procedure.
name | Required. Name of the Property Set procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Let procedure in the same module.
arglist | Required. List of variables representing arguments that are passed to the Property Set procedure when it is called. Multiple arguments are separated by commas.
reference | Required. Variable containing the object reference used on the right side of the object reference assignment.
statements | Optional. Any group of statements to be executed within the body of the Property procedure.

The arglist argument has the following syntax and parts:

[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]

Part | Description
Optional | Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Note that it is not possible for the right side of a Property Set expression to be Optional.
ByVal | Optional. Indicates that the argument is passed by value.
ByRef | Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.
ParamArray | Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.
varname | Required. Name of the variable representing the argument; follows standard variable naming conventions.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable length only), Object, Variant, or a specific object type. If the parameter is not Optional, a user-defined type may also be specified.
defaultvalue | Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.
Note Note

Every Property Set statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) contains the actual object reference for the property when the procedure defined by the Property Set statement is invoked. It is referred to as reference in the preceding syntax. It can't be Optional.

Remarks

If not explicitly specified using Public, Private, or Friend, Property procedures are public by default. If Static isn't used, the value of local variables is not preserved between calls. The Friend keyword can only be used in class modules. However, Friend procedures can be accessed by procedures in any module of a project. A Friend procedure doesn't appear in the type library of its parent class, nor can a Friend procedure be late bound.

All executable code must be in procedures. You can't define a Property Set procedure inside another Property, Sub, or Function procedure.

The Exit Property statement causes an immediate exit from a Property Set procedure. Program execution continues with the statement following the statement that called the Property Set procedure. Any number of Exit Property statements can appear anywhere in a Property Set procedure.

Like a Function and Property Get procedure, a Property Set procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and Property Get procedure, both of which return a value, you can only use a Property Set procedure on the left side of an object reference assignment (Set statement).

Example

This example uses the Property Set statement to define a property procedure that sets a reference to an object.

Copy code Copy code
' The Pen property may be set to different Pen implementations.
Property Set Pen(P As Object)
 Set CurrentPen = P ' Assign Pen to object.
End Property


Public Statement

 Copy code hover
[image]

Public Statement
Send feedback

Used at module level to declare public variables and allocate storage space.

Syntax

Public [WithEvents] varname[([subscripts])] [As [New] type] [,[WithEvents] varname[([subscripts])] [As [New] type]] . . .

The Public statement syntax has these parts:

Part | Description
WithEvents | Optional. Keyword specifying that varname is an object variable used to respond to events triggered by an ActiveX object. WithEvents is valid only in class modules. You can declare as many individual variables as you like using WithEvents, but you can't create arrays with WithEvents. You can't use New with WithEvents.
varname | Required. Name of the variable; follows standard naming conventions.
subscripts | Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax: [lower To] upper [,[lower To] upper] . . . When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
New | Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don't have to use the Set statement to assign the object reference. The New keyword can't be used to declare variables of any intrinsic data type, can't be used to declare instances of dependent objects, and can't be used with WithEvents.
type | Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String, (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable being defined.

Remarks

Variables declared using the Public statement are available to all procedures in all modules in all applications unless Option Private Module is in effect; in which case, the variables are public only within the project in which they reside.

The Public statement can't be used in a class module to declare a fixed-length string variable.

Use the Public statement to declare the data type of a variable. For example, the following statement declares a variable as an Integer:

Copy code Copy code
Public NumberOfEmployees As Integer

Also use a Public statement to declare the object type of a variable. The following statement declares a variable for a new instance of a worksheet.

Copy code Copy code
Public X As New Worksheet

If the New keyword is not used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object.

You can also use the Public statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

If you don't specify a data type or object type and there is no Def type statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

Example

This example uses the Public statement at the module level (General section) of a standard module to explicitly declare variables as public; that is, they are available to all procedures in all modules in all applications unless Option Private Module is in effect.

Copy code Copy code
                      Public Number As Integer ' Public Integer variable.
Public NameArray(1 To 5) As String ' Public array variable.
' Multiple declarations, two Variants and one Integer, all Public.
Public MyVar, YourVar, ThisVar As Integer


Put Statement

 Copy code hover
[image]

Put Statement
Send feedback

Writes data from a variable to a disk file.

Syntax

Put [#]filenumber, [recnumber], varname

The Put statement syntax has these parts:

Part | Description
filenumber | Required. Any valid file number.
recnumber | Optional. Variant (Long). Record number (Random mode files) or byte number (Binary mode files) at which writing begins.
varname | Required. Name of variable containing data to be written to disk.

Remarks

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

The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit recnumber, the next record or byte after the last Get or Put statement or pointed to by the last Seek function is written. You must include delimiting commas, for example:

Copy code Copy code
                      Put #4,,FileBuffer

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

  • If the length of the data being written is less than the length specified in the Len clause of the Open statement, Put writes subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being written. If the length of the data being written is greater than the length specified in the Len clause of the Open statement, an error occurs.

  • If the variable being written is a variable-length string, Put writes a 2-byte descriptor containing the string length and then the variable. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.

  • If the variable being written is a Variant of a numeric type, Put writes 2 bytes identifying the VarType of the Variant and then writes the variable. For example, when writing a Variant of VarType 3, Put writes 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.

    Note Note

    You can use the Put statement to write a Variant array to disk, but you can't use Put to write a scalar Variant containing an array to disk. You also can't use Put to write objects to disk.

  • If the variable being written is a Variant of VarType 8 (String), Put writes 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then writes the string data. The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string.

  • If the variable being written is a dynamic array, Put writes a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the array data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written to disk.

    Copy code Copy code
    Dim MyArray(1 To 5,1 To 10) As Integer

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

  • If the variable being written is a fixed-size array, Put writes only the data. No descriptor is written to disk.

  • If the variable being written is any other type of variable (not a variable-length string or a Variant), Put writes only the variable data. The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being written.

  • Put writes elements of user-defined types as if each were written individually, except there is no padding between elements. On disk, a dynamic array in a user-defined type written with Put is prefixed by a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the individual elements, including any arrays and their descriptors.

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

  • The Len clause in the Open statement has no effect. Put writes all variables to disk contiguously; that is, with no padding between records.

  • For any array other than an array in a user-defined type, Put writes only the data. No descriptor is written.

  • Put writes variable-length strings that are not elements of user-defined types without the 2-byte length descriptor. The number of bytes written equals the number of characters in the string. For example, the following statements write 10 bytes to file number 1:

    Copy code Copy code
    VarString$ = String$(10," ")
Put #1,,VarString$

Example

This example uses the Put statement to write data to a file. Five records of the user-defined type are written to the file.

Copy code Copy code
Type Record ' Define user-defined type.
 ID As Integer
 Name As String * 20
End Type

Dim MyRecord As Record, RecordNumber ' Declare variables.
' Open file for random access.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
For RecordNumber = 1 To 5 ' Loop 5 times.
 MyRecord.ID = RecordNumber ' Define ID.
 MyRecord.Name = "My Name" & RecordNumber ' Create a string.
 Put #1, RecordNumber, MyRecord ' Write record to file.
Next RecordNumber
Close #1 ' Close file.


RaiseEvent Statement

 Copy code hover
[image]

RaiseEvent Statement
Send feedback

Fires an event declared at module level within a class, form, or document.

Syntax

RaiseEvent eventname [(argumentlist)]

The required eventname is the name of an event declared within the module and follows Basic variable naming conventions.

The RaiseEvent statement syntax has these parts:

Part | Description
eventname | Required. Name of the event to fire.
argumentlist | Optional. Comma-delimited list of variables, arrays, or expressions The argumentlist must be enclosed by parentheses. If there are no arguments, the parentheses must be omitted.

Remarks

If the event has not been declared within the module in which it is raised, an error occurs. The following fragment illustrates an event declaration and a procedure in which the event is raised.

Copy code Copy code
' Declare an event at module level of a class module
Event LogonCompleted (UserName as String)

Sub
 ' Raise the event.
 RaiseEvent LogonCompleted ("AntoineJan")
End Sub

If the event has no arguments, including empty parentheses, in the RaiseEvent, invocation of the event causes an error. You can't use RaiseEvent to fire events that are not explicitly declared in the module. For example, if a form has a Click event, you can't fire its Click event using RaiseEvent. If you declare a Click event in the form module, it shadows the form's own Click event. You can still invoke the form's Click event using normal syntax for calling the event, but not using the RaiseEvent statement.

Event firing is done in the order that the connections are established. Since events can have ByRef parameters, a process that connects late may receive parameters that have been changed by an earlier event handler.

Example

The following example uses events to count off seconds during a demonstration of the fastest 100 meter race. The code illustrates all of the event-related methods, properties, and statements, including the RaiseEvent statement.

The class that raises an event is the event source, and the classes that implement the event are the sinks. An event source can have multiple sinks for the events it generates. When the class raises the event, that event is fired on every class that has elected to sink events for that instance of the object.

The example also uses a form (Form1 ) with a button (Command1 ), a label (Label1 ), and two text boxes (Text1 and ) with a button (Command1 ), a label (Label1 ), and two text boxes (Text1 and Text2 ). When you click the button, the first text box displays "From Now" and the second starts to count seconds. When the full time (9.84 seconds) has elapsed, the first text box displays "Until Now" and the second displays "9.84"

The code for specifies the initial and terminal states of the form. It also contains the code executed when events are raised.

Copy code Copy code
Option Explicit

Private WithEvents mText As TimerState

Private Sub Command1_Click()
 Text1.Text = "From Now"
 Text1.Refresh
 Text2.Text = "0"
 Text2.Refresh
 Call mText.TimerTask(9.84)
End Sub

Private Sub Form_Load()
 Command1.Caption = "Click to Start Timer"
 Text1.Text = ""
 Text2.Text = ""
 Label1.Caption = "The fastest 100 meters ever run took this long:"
 Set mText = New TimerState
 End Sub

Private Sub mText_ChangeText()
 Text1.Text = "Until Now"
 Text2.Text = "9.84"
End Sub

Private Sub mText_UpdateTime(ByVal dblJump As Double)
 Text2.Text = Str(Format(dblJump, "0"))
 DoEvents
End Sub

The remaining code is in a class module named TimerState. Included among the commands in this module are the Raise Event statements.

Copy code Copy code
Option Explicit
Public Event UpdateTime(ByVal dblJump As Double)
Public Event ChangeText()

Public Sub TimerTask(ByVal Duration As Double)
 Dim dblStart As Double
 Dim dblSecond As Double
 Dim dblSoFar As Double
 dblStart = Timer
 dblSoFar = dblStart

 Do While Timer < dblStart + Duration
 If Timer - dblSoFar >= 1 Then
 dblSoFar = dblSoFar + 1
 RaiseEvent UpdateTime(Timer - dblStart)
 End If
 Loop

 RaiseEvent ChangeText

End Sub


Randomize Statement

 Copy code hover
[image]

Randomize Statement
Send feedback

Initializes the random-number generator.

Syntax

Randomize [number]

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

Remarks

Randomize uses number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit number, the value returned by the system timer is used as the new seed value.

If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and thereafter uses the last generated number as a seed value.

Note Note

To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.

Example

This example uses the Randomize statement to initialize the random-number generator. Because the number argument has been omitted, Randomize uses the return value from the Timer function as the new seed value.

Copy code Copy code
Dim MyValue
Randomize ' Initialize random-number generator.

MyValue = Int((6 * Rnd) + 1) ' Generate random value between 1 and 6.


ReDim Statement

 Copy code hover
[image]

ReDim Statement
Send feedback

Used at procedure level to reallocate storage space for dynamic array variables.

Syntax

ReDim [Preserve] varname(subscripts) [As type] [, varname(subscripts) [As type]] . . .

The ReDim statement syntax has these parts:

Part | Description
Preserve | Optional. Keyword used to preserve the data in an existing array when you change the size of the last dimension.
varname | Required. Name of the variable; follows standard variable naming conventions.
subscripts | Required. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax: [lower To] upper [,[lower To] upper] . . . When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
type | Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable being defined. For a Variant containing an array, type describes the type of each element of the array, but doesn't change the Variant to some other type.

Remarks

The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts).

You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array. However, you can't declare an array of one data type and later use ReDim to change the array to another data type, unless the array is contained in a Variant. If the array is contained in a Variant, the type of the elements can be changed using an As type clause, unless you're using the Preserve keyword, in which case, no changes of data type are permitted.

If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array. The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.

Copy code Copy code
ReDim X(10, 10, 10)
. . .
ReDim Preserve X(10, 10, 15)

Similarly, when you use Preserve, you can change the size of the array only by changing the upper bound; changing the lower bound causes an error.

If you make an array smaller than it was, data in the eliminated elements will be lost. If you pass an array to a procedure by reference, you can't redimension the array within the procedure.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable. A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object.

The ReDim statement acts as a declarative statement if the variable it declares doesn't exist at module level or procedure level. If another variable with the same name is created later, even in a wider scope, ReDim will refer to the later variable and won't necessarily cause a compilation error, even if Option Explicit is in effect. To avoid such conflicts, ReDim should not be used as a declarative statement, but simply for redimensioning arrays.

Note Note

To resize an array contained in a Variant, you must explicitly declare the Variant variable before attempting to resize its array.

Example

This example uses the ReDim statement to allocate and reallocate storage space for dynamic-array variables. It assumes the Option Base is 1.

Copy code Copy code
Dim MyArray() As Integer ' Declare dynamic array.
Redim MyArray(5) ' Allocate 5 elements.
For I = 1 To 5 ' Loop 5 times.
 MyArray(I) = I ' Initialize array.
Next I

The next statement resizes the array and erases the elements.

Copy code Copy code
                      Redim MyArray(10) ' Resize to 10 elements.
For I = 1 To 10 ' Loop 10 times.
 MyArray(I) = I ' Initialize array.
Next I

The following statement resizes the array but does not erase elements.

Copy code Copy code
                      Redim Preserve MyArray(15) ' Resize to 15 elements.


Rem Statement

 Copy code hover
[image]

Rem Statement
Send feedback

Used to include explanatory remarks in a program.

Syntax

Rem comment

You can also use the following syntax:

' comment

The optional comment argument is the text of any comment you want to include. A space is required between the Rem keyword and comment.

Remarks

If you use line numbers or line labels, you can branch from a GoTo or GoSub statement to a line containing a Rem statement. Execution continues with the first executable statement following the Rem statement. If the Rem keyword follows other statements on a line, it must be separated from the statements by a colon (:).

You can use an apostrophe (') instead of the Rem keyword. When you use an apostrophe, the colon is not required after other statements.

Example

This example illustrates the various forms of the Rem statement, which is used to include explanatory remarks in a program.

Copy code Copy code
Dim MyStr1, MyStr2
MyStr1 = "Hello": Rem Comment after a statement separated by a colon.
MyStr2 = "Goodbye" ' This is also a comment; no colon is needed.


Reset Statement

 Copy code hover
[image]

Reset Statement
Send feedback

Closes all disk files opened using the Open statement.

Syntax

Reset

Remarks

The Reset statement closes all active files opened by the Open statement and writes the contents of all file buffers to disk.

Example

This example uses the Reset statement to close all open files and write the contents of all file buffers to disk. Note the use of the Variant variable as both a string and a number.

Copy code Copy code
Dim FileNumber
For FileNumber = 1 To 5 ' Loop 5 times.
 ' Open file for output. FileNumber is concatenated into the string
 ' TEST for the file name, but is a number following a #.
 Open "TEST" & FileNumber For Output As #FileNumber
 Write #FileNumber, "Hello World" ' Write data to file.
Next FileNumber
Reset ' Close files and write contents
 ' to disk.


Resume Statement

 Copy code hover
[image]

Resume Statement
Send feedback

Resumes execution after an error-handling routine is finished.

Syntax

Resume [0]

Resume Next

Resume line

The Resume statement syntax can have any of the following forms:

Statement | Description
Resume | If the error occurred in the same procedure as the error handler, execution resumes with the statement that caused the error. If the error occurred in a called procedure, execution resumes at the statement that last called out of the procedure containing the error-handling routine.
Resume Next | If the error occurred in the same procedure as the error handler, execution resumes with the statement immediately following the statement that caused the error. If the error occurred in a called procedure, execution resumes with the statement immediately following the statement that last called out of the procedure containing the error-handling routine (or On Error Resume Next statement).
Resume line | Execution resumes at line specified in the required line argument. The line argument is a line label or line number and must be in the same procedure as the error handler.

Remarks

If you use a Resume statement anywhere except in an error-handling routine, an error occurs.

Example

This example uses the Resume statement to end error handling in a procedure, and then resume execution with the statement that caused the error. Error number 55 is generated to illustrate using the Resume statement.

Copy code Copy code
Sub ResumeStatementDemo()
 On Error GoTo ErrorHandler ' Enable error-handling routine.
 Open "TESTFILE" For Output As #1 ' Open file for output.
 Kill "TESTFILE" ' Attempt to delete open file.
 Exit Sub ' Exit Sub to avoid error handler.
ErrorHandler: ' Error-handling routine.
 Select Case Err.Number ' Evaluate error number.
 Case 55 ' "File already open" error.
 Close #1 ' Close open file.
 Case Else
 ' Handle other situations here....
 End Select
 Resume ' Resume execution at same line
 ' that caused the error.
End Sub


RmDir Statement

 Copy code hover
[image]

RmDir Statement
Send feedback

Removes an existing directory or folder.

Syntax

RmDir path

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

Remarks

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

Example

This example uses the RmDir statement to remove an existing directory or folder.

Copy code Copy code
' Assume that MYDIR is an empty directory or folder.
RmDir "MYDIR" ' Remove MYDIR.


RSet Statement

 Copy code hover
[image]

RSet Statement
Send feedback

Right aligns a string within a string variable.

Syntax

RSet stringvar = string

The RSet statement syntax has these parts:

Part | Description
stringvar | Required. Name of string variable.
string | Required. String expression to be right-aligned within stringvar.

Remarks

If stringvar is longer than string, RSet replaces any leftover characters in stringvar with spaces, back to its beginning.

Note Note

RSet can't be used with user-defined types.

Example

This example uses the RSet statement to right align a string within a string variable.

Copy code Copy code
Dim MyString
MyString = "0123456789" ' Initialize string.
Rset MyString = "Right->" ' MyString contains " Right->".


SaveSetting Statement

 Copy code hover
[image]

SaveSetting Statement
Send feedback

Saves or creates an application entry in the application's entry in the Windows registry or (on the Macintosh) information in the application's initialization file.

Syntax

SaveSetting appname, section, key, setting

The SaveSetting statement syntax has these named arguments:

Part | Description
appname | Required. String expression containing the name of the application or project to which the setting applies. On the Macintosh, this is the filename of the initialization file in the Preferences folder in the System folder.
section | Required. String expression containing the name of the section where the key setting is being saved.
key | Required. String expression containing the name of the key setting being saved.
setting | Required. Expression containing the value that key is being set to.

Remarks

An error occurs if the key setting can't be saved for any reason.

Example

The following example first uses the SaveSetting statement to make entries in the Windows registry (or .ini file on 16-bit Windows platforms) for the application, and then uses the DeleteSetting statement to remove them.

Copy code Copy code
' Place some settings in the registry.
SaveSetting appname := "MyApp", section := "Startup", _
 key := "Top", setting := 75
SaveSetting "MyApp","Startup", "Left", 50
' Remove section and all its settings from registry.
DeleteSetting "MyApp", "Startup"


Seek Statement

 Copy code hover
[image]

Seek Statement
Send feedback

Sets the position for the next read/write operation within a file opened using the Open statement.

Syntax

Seek [#]filenumber, position

The Seek statement syntax has these parts:

Part | Description
filenumber | Required. Any valid file number.
position | Required. Number in the range 1 - 2,147,483,647, inclusive, that indicates where the next read/write operation should occur.

Remarks

Record numbers specified in Get and Put statements override file positioning performed by Seek.

Performing a file-write operation after a Seek operation beyond the end of a file extends the file. If you attempt a Seek operation to a negative or zero position, an error occurs.

Example

This example uses the Seek statement to set the position for the next read or write within a file. This example assumes TESTFILE is a file containing records of the user-defined type is a file containing records of the user-defined type Record .

Copy code Copy code
Type Record ' Define user-defined type.
 ID As Integer
 Name As String * 20
End Type

For files opened in Random mode, Seek sets the next record.

Copy code Copy code
Dim MyRecord As Record, MaxSize, RecordNumber ' Declare variables.
' Open file in random-file mode.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
MaxSize = LOF(1) \ Len(MyRecord) ' Get number of records in file.
' The loop reads all records starting from the last.
For RecordNumber = MaxSize To 1 Step - 1
 Seek #1, RecordNumber ' Set position.
 Get #1, , MyRecord ' Read record.
Next RecordNumber
Close #1 ' Close file.

For files opened in modes other than Random mode, Seek sets the byte position at which the next operation takes place. Assume is a file containing a few lines of text.

Copy code Copy code
Dim MaxSize, NextChar, MyChar
Open "TESTFILE" For Input As #1 ' Open file for input.
MaxSize = LOF(1) ' Get size of file in bytes.
' The loop reads all characters starting from the last.
For NextChar = MaxSize To 1 Step -1
 Seek #1, NextChar ' Set position.
 MyChar = Input(1, #1) ' Read character.
Next NextChar
Close #1 ' Close file.


Select Case Statement

 Copy code hover
[image]

Select Case Statement
Send feedback

Executes one of several groups of statements, depending on the value of an expression.

Syntax

Select Case testexpression
[Case expressionlist-n
[statements-n]]
[Case Else
[elsestatements]]

End Select

The Select Case statement syntax has these parts:

Part | Description
testexpression | Required. Any numeric expression or string expression.
expressionlist-n | Required if a Case appears. Delimited list of one or more of the following forms: expression, expression To expression, Is comparisonoperator expression. The To keyword specifies a range of values. If you use the To keyword, the smaller value must appear before To. Use the Is keyword with comparison operators (except Is and Like) to specify a range of values. If not supplied, the Is keyword is automatically inserted.
statements-n | Optional. One or more statements executed if testexpression matches any part of expressionlist-n.
elsestatements | Optional. One or more statements executed if testexpression doesn't match any of the Case clause.

Remarks

If testexpression matches any Case expressionlist expression, the statements following that Case clause are executed up to the next Case clause, or, for the last clause, up to End Select. Control then passes to the statement following End Select. If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed.

The Case Else clause is used to indicate the elsestatements to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections. Although not required, it is a good idea to have a Case Else statement in your Select Case block to handle unforeseen testexpression values. If no Case expressionlist matches testexpression and there is no Case Else statement, execution continues at the statement following End Select.

You can use multiple expressions or ranges in each Case clause. For example, the following line is valid:

Copy code Copy code
Case 1 To 4, 7 To 9, 11, 13, Is > MaxNumber
Note Note

The Is comparison operator is not the same as the Is keyword used in the Select Case statement.

You also can specify ranges and multiple expressions for character strings. In the following example, Case matches strings that are exactly equal to everything , strings that fall between nuts and soup in alphabetic order, and the current value of TestItem :

Copy code Copy code
Case "everything", "nuts" To "soup", TestItem

Select Case statements can be nested. Each nested Select Case statement must have a matching End Select statement.

Example

This example uses the Select Case statement to evaluate the value of a variable. The second Case clause contains the value of the variable being evaluated, and therefore only the statement associated with it is executed.

Copy code Copy code
Dim Number
Number = 8    ' Initialize variable.
Select Case Number    ' Evaluate Number.
Case 1 To 5    ' Number between 1 and 5, inclusive.
    Debug.Print "Between 1 and 5"
' The following is the only Case clause that evaluates to True.
Case 6, 7, 8    ' Number between 6 and 8.
    Debug.Print "Between 6 and 8"
Case 9 To 10    ' Number is 9 or 10.
Debug.Print "Greater than 8"
Case Else    ' Other values.
    Debug.Print "Not between 1 and 10"
End Select


SendKeys Statement

 Copy code hover
[image]

SendKeys Statement
Send feedback

Sends one or more keystrokes to the active window as if typed at the keyboard.

Syntax

SendKeys string [, wait]

The SendKeys statement syntax has these named arguments:

Part | Description
string | Required. String expression specifying the keystrokes to send.
Wait | Optional. Boolean value specifying the wait mode. If False (default), control is returned to the procedure immediately after the keys are sent. If True, keystrokes must be processed before control is returned to the procedure.

Remarks

Each key is represented by one or more characters. To specify a single keyboard character, use the character itself. For example, to represent the letter A, use "A" for string. To represent more than one character, append each additional character to the one preceding it. To represent the letters A, B, and C, use "ABC" for string.

The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses ( ) have special meanings to SendKeys. To specify one of these characters, enclose it within braces ({}). For example, to specify the plus sign, use {+}. Brackets ([ ]) have no special meaning to SendKeys, but you must enclose them in braces. In other applications, brackets do have a special meaning that may be significant when dynamic data exchange (DDE) occurs. To specify brace characters, use {{} and {}}.

To specify characters that aren't displayed when you press a key, such as ENTER or TAB, and keys that represent actions rather than characters, use the codes shown below:

Key | Code
BACKSPACE | {BACKSPACE}, {BS}, or{BKSP}
BREAK | {BREAK}
CAPS LOCK | {CAPSLOCK}
DEL or DELETE | {DELETE} or{DEL}
DOWN ARROW | {DOWN}
END | {END}
ENTER | {ENTER} or ~
ESC | {ESC}
HELP | {HELP}
HOME | {HOME}
INS or INSERT | {INSERT} or {INS}
LEFT ARROW | {LEFT}
NUM LOCK | {NUMLOCK}
PAGE DOWN | {PGDN}
PAGE UP | {PGUP}
PRINT SCREEN | {PRTSC}
RIGHT ARROW | {RIGHT}
SCROLL LOCK | {SCROLLLOCK}
TAB | {TAB}
UP ARROW | {UP}
F1 | {F1}
F2 | {F2}
F3 | {F3}
F4 | {F4}
F5 | {F5}
F6 | {F6}
F7 | {F7}
F8 | {F8}
F9 | {F9}
F10 | {F10}
F11 | {F11}
F12 | {F12}
F13 | {F13}
F14 | {F14}
F15 | {F15}
F16 | {F16}

To specify keys combined with any combination of the SHIFT, CTRL, and ALT keys, precede the key code with one or more of the following codes:

Key | Code
SHIFT | +
CTRL | ^
ALT | %

To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses. For example, to specify to hold down SHIFT while E and C are pressed, use "+(EC)". To specify to hold down SHIFT while E is pressed, followed by C without SHIFT, use "". To specify to hold down SHIFT while E is pressed, followed by C without SHIFT, use "+EC".

To specify repeating keys, use the form {key number}. You must put a space between key and number. For example, {LEFT 42} means press the LEFT ARROW key 42 times; {h 10} means press H 10 times.

Note Note

You can't use SendKeys to send keystrokes to an application that is not designed to run in Microsoft Windows or Macintosh. Sendkeys also can't send the PRINT SCREEN key {PRTSC} to any application.

Example

This example uses the Shell function to run the Calculator application included with Microsoft Windows. It uses the SendKeys statement to send keystrokes to add some numbers, and then quit the Calculator. (To see the example, paste it into a procedure, then run the procedure. Because AppActivate changes the focus to the Calculator application, you can't single step through the code.). On the Macintosh, use a Macintosh application that accepts keyboard input instead of the Windows Calculator.

Copy code Copy code
Dim ReturnValue, I
ReturnValue = Shell("CALC.EXE", 1)    ' Run Calculator.
AppActivate ReturnValue     ' Activate the Calculator.
For I = 1 To 100    ' Set up counting loop.
    SendKeys I & "{+}", True    ' Send keystrokes to Calculator
Next I    ' to add each value of I.
SendKeys "=", True    ' Get grand total.
SendKeys "%{F4}", True    ' Send ALT+F4 to close Calculator.


Set Statement

 Copy code hover
[image]

Set Statement
Send feedback

Assigns an object reference to a variable or property.

Syntax

Set objectvar = {[New] objectexpression | Nothing}

The Set statement syntax has these parts:

Part | Description
objectvar | Required. Name of the variable or property; follows standard variable naming conventions.
New | Optional. New is usually used during declaration to enable implicit object creation. When New is used with Set, it creates a new instance of the class. If objectvar contained a reference to an object, that reference is released when the new one is assigned. The New keyword can't be used to create new instances of any intrinsic data type and can't be used to create dependent objects.
objectexpression | Required. Expression consisting of the name of an object, another declared variable of the same object type, or a function or method that returns an object of the same object type.
Nothing | Optional. Discontinues association of objectvar with any specific object. Assigning Nothing to objectvar releases all the system and memory resources associated with the previously referenced object when no other variable refers to it.

Remarks

To be valid, objectvar must be an object type consistent with the object being assigned to it.

The Dim, Private, Public, ReDim, and Static statements only declare a variable that refers to an object. No actual object is referred to until you use the Set statement to assign a specific object.

The following example illustrates how Dim is used to declare an array with the type Form1. No instance of Form1 actually exists. Set then assigns references to new instances of Form1 to the . No instance of Form1 actually exists. Set then assigns references to new instances of Form1 to the myChildForms variable. Such code might be used to create child forms in an MDI application.

Copy code Copy code
Dim myChildForms(1 to 4) As Form1
Set myChildForms(1) = New Form1
Set myChildForms(2) = New Form1
Set myChildForms(3) = New Form1
Set myChildForms(4) = New Form1

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 such variables are references to the object rather than copies of the object, any change in the object is reflected in all variables that refer to it. However, when you use the New keyword in the Set statement, you are actually creating an instance of the object.

Example

This example uses the Set statement to assign object references to variables. YourObject is assumed to be a valid object with a Text property.

Copy code Copy code
Dim YourObject, MyObject, MyStr
Set MyObject = YourObject    ' Assign object reference.
' MyObject and YourObject refer to the same object.
YourObject.Text = "Hello World"    ' Initialize property.
MyStr = MyObject.Text    ' Returns "Hello World".

' Discontinue association. MyObject no longer refers to YourObject.
Set MyObject = Nothing    ' Release the object.


SetAttr Statement

 Copy code hover
[image]

SetAttr Statement
Send feedback

Sets attribute information for a file.

Syntax

SetAttr pathname, attributes

The SetAttr statement syntax has these named arguments:

Part | Description
pathname | Required. String expression that specifies a file name — may include directory or folder, and drive.
attributes | Required. Constant or numeric expression, whose sum specifies file attributes.

Settings

The attributes argument settings are:

Constant | Value | Description
vbNormal | 0 | Normal (default).
vbReadOnly | 1 | Read-only.
vbHidden | 2 | Hidden.
vbSystem | 4 | System file. Not available on the Macintosh.
vbArchive | 32 | File has changed since last backup.
vbAlias | 64 | Specified file name is an alias. Available only on the Macintosh.
Note Note

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

Remarks

A run-time error occurs if you try to set the attributes of an open file.

Example

This example uses the SetAttr statement to set attributes for a file. On the Macintosh, only the constants vbNormal, vbReadOnly, vbHidden and vbAlias are available.

Copy code Copy code
                      SetAttr "TESTFILE", vbHidden ' Set hidden attribute.
SetAttr "TESTFILE", vbHidden + vbReadOnly ' Set hidden and read-only
 ' attributes.


Static Statement

 Copy code hover
[image]

Static Statement
Send feedback

Used at procedure level to declare variables and allocate storage space. Variables declared with the Static statement retain their values as long as the code is running.

Syntax

Static varname[([subscripts])] [As [New] type] [, varname[([subscripts])] [As [New] type]] . . .

The Static statement syntax has these parts:

Part | Description
varname | Required. Name of the variable; follows standard variable naming conventions.
subscripts | Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax: [lower To] upper [,[lower To] upper] . . . When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
New | Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don't have to use the Set statement to assign the object reference. The New keyword can't be used to declare variables of any intrinsic data type and can't be used to declare instances of dependent objects.
type | Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String, (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable being defined.

Remarks

Once module code is running, variables declared with the Static statement retain their value until the module is reset or restarted. In class modules, variables declared with the Static statement retain their value in each class instance until that instance is destroyed. In form modules, static variables retain their value until the form is closed. Use the Static statement in nonstatic procedures to explicitly declare variables that are visible only within the procedure, but whose lifetime is the same as the module in which the procedure is defined.

Use a Static statement within a procedure to declare the data type of a variable that retains its value between procedure calls. For example, the following statement declares a fixed-size array of integers:

Copy code Copy code
Static EmployeeNumber(200) As Integer

The following statement declares a variable for a new instance of a worksheet:

Copy code Copy code
Static X As New Worksheet

If the New keyword isn't used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object. When you use the New keyword in the declaration, an instance of the object is created on the first reference to the object.

If you don't specify a data type or object type, and there is no Def type statement in the module, the variable is Variant by default.

Note Note

The Static statement and the Static keyword are similar, but used for different effects. If you declare a procedure using the Static keyword (as in Static Sub CountSales ()), the storage space for all local variables within the procedure is allocated once, and the value of the variables is preserved for the entire time the program is running. For nonstatic procedures, storage space for variables is allocated each time the procedure is called and released when the procedure is exited. The Static statement is used to declare specific variables within nonstatic procedures to preserve their value for as long as the program is running.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

Note Note

When you use Static statements within a procedure, put them at the beginning of the procedure with other declarative statements such as Dim.

Example

This example uses the Static statement to retain the value of a variable for as long as module code is running.

Copy code Copy code
' Function definition.
Function KeepTotal(Number)
    ' Only the variable Accumulate preserves its value between calls.
    Static Accumulate
    Accumulate = Accumulate + Number
    KeepTotal = Accumulate
End Function

' Static function definition.
Static Function MyFunction(Arg1, Arg2, Arg3)
    ' All local variables preserve value between function calls.
    Accumulate = Arg1 + Arg2 + Arg3
    Half = Accumulate / 2
    MyFunction = Half
End Function


Stop Statement

 Copy code hover
[image]

Stop Statement
Send feedback

Suspends execution.

Syntax

Stop

Remarks

You can place Stop statements anywhere in procedures to suspend execution. Using the Stop statement is similar to setting a breakpoint in the code.

The Stop statement suspends execution, but unlike End, it doesn't close any files or clear variables, unless it is in a compiled executable (.exe) file.

Example

This example uses the Stop statement to suspend execution for each iteration through the For...Next loop.

Copy code Copy code
Dim I
For I = 1 To 10 ' Start For...Next loop.
 Debug.Print I ' Print I to the Immediate window.
 Stop ' Stop during each iteration.
Next I


Sub Statement

 Copy code hover
[image]

Sub Statement
Send feedback

Declares the name, arguments, and code that form the body of a Sub procedure.

Syntax

[Private | Public | Friend] [Static] Sub name [(arglist)]
[statements]
[Exit Sub]
[statements]

End Sub

The Sub statement syntax has these parts:

Part | Description
Public | Optional. Indicates that the Sub procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private statement, the procedure is not available outside the project.
Private | Optional. Indicates that the Sub procedure is accessible only to other procedures in the module where it is declared.
Friend | Optional. Used only in a class module. Indicates that the Sub procedure is visible throughout the project, but not visible to a controller of an instance of an object.
Static | Optional. Indicates that the Sub procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Sub, even if they are used in the procedure.
name | Required. Name of the Sub; follows standard variable naming conventions.
arglist | Optional. List of variables representing arguments that are passed to the Sub procedure when it is called. Multiple variables are separated by commas.
statements | Optional. Any group of statements to be executed within the Sub procedure.

The arglist argument has the following syntax and parts:

[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]

Part | Description
Optional | Optional. Keyword indicating that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used.
ByVal | Optional. Indicates that the argument is passed by value.
ByRef | Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.
ParamArray | Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. ParamArray can't be used with ByVal, ByRef, or Optional.
varname | Required. Name of the variable representing the argument; follows standard variable naming conventions.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable-length only), Object, Variant, or a specific object type. If the parameter is not Optional, a user-defined type may also be specified.
defaultvalue | Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

Remarks

If not explicitly specified using Public, Private, or Friend, Sub procedures are public by default. If Static isn't used, the value of local variables is not preserved between calls. The Friend keyword can only be used in class modules. However, Friend procedures can be accessed by procedures in any module of a project. A Friend procedure doesn't appear in the type library of its parent class, nor can a Friend procedure be late bound.

Sub procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword usually is not used with recursive Sub procedures.

All executable code must be in procedures. You can't define a Sub procedure inside another Sub, Function, or Property procedure.

The Exit Sub keywords cause an immediate exit from a Sub procedure. Program execution continues with the statement following the statement that called the Sub procedure. Any number of Exit Sub statements can appear anywhere in a Sub procedure.

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function procedure, which returns a value, a Sub procedure can't be used in an expression.

You call a Sub procedure using the procedure name followed by the argument list. See the Call statement for specific information on how to call Sub procedures.

Variables used in Sub procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name. To avoid this kind of conflict, explicitly declare variables. You can use an Option Explicit statement to force explicit declaration of variables.

Note Note

You can't use GoSub, GoTo, or Return to enter or exit a Sub procedure.

Example

This example uses the Sub statement to define the name, arguments, and code that form the body of a Sub procedure.

Copy code Copy code
' Sub procedure definition.
' Sub procedure with two arguments.
Sub SubComputeArea(Length, TheWidth)
 Dim Area As Double ' Declare local variable.
 If Length = 0 Or TheWidth = 0 Then
 ' If either argument = 0.
 Exit Sub ' Exit Sub immediately.
 End If
 Area = Length * TheWidth ' Calculate area of rectangle.
 Debug.Print Area ' Print Area to Debug window.
End Sub


Time Statement

 Copy code hover
[image]

Time Statement
Send feedback

Sets the system time.

Syntax

Time = time

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

Remarks

If time is a string, Time attempts to convert it to a time using the time separators you specified for your system. If it can't be converted to a valid time, an error occurs.

Example

This example uses the Time statement to set the computer system time to a user-defined time.

Copy code Copy code
Dim MyTime
MyTime = #4:35:17 PM# ' Assign a time.
Time = MyTime ' Set system time to MyTime.


Type Statement

 Copy code hover
[image]

Type Statement
Send feedback

Used at module level to define a user-defined data type containing one or more elements.

Syntax

[Private | Public] Type varname
elementname [([subscripts])] As type
[elementname [([subscripts])] As type]
. . .

End Type

The Type statement syntax has these parts:

Part | Description
Public | Optional. Used to declare user-defined types that are available to all procedures in all modules in all projects.
Private | Optional. Used to declare user-defined types that are available only within the module where the declaration is made.
varname | Required. Name of the user-defined type; follows standard variable naming conventions.
elementname | Required. Name of an element of the user-defined type. Element names also follow standard variable naming conventions, except that keywords can be used.
subscripts | When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
type | Required. Data type of the element; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, another user-defined type, or an object type.

Remarks

The Type statement can be used only at module level. Once you have declared a user-defined type using the Type statement, you can declare a variable of that type anywhere within the scope of the declaration. Use Dim, Private, Public, ReDim, or Static to declare a variable of a user-defined type.

In standard modules and class modules, user-defined types are public by default. This visibility can be changed using the Private keyword.

Line numbers and line labels aren't allowed in Type...End Type blocks.

User-defined types are often used with data records, which frequently consist of a number of related elements of different data types.

The following example shows the use of fixed-size arrays in a user-defined type:

VBA Copy code Copy code
                      Type StateData
    CityCode (1 To 100) As Integer    ' Declare a static array.
    County As String * 30
End Type

Dim Washington(1 To 100) As StateData

In the preceding example, StateData includes the CityCode static array, and the record Washington has the same structure as StateData.

When you declare a fixed-size array within a user-defined type, its dimensions must be declared with numeric literals or constants rather than variables.

Example

This example uses the Type statement to define a user-defined data type. The Type statement is used at the module level only. If it appears in a class module, a Type statement must be preceded by the keyword Private.

VBA Copy code Copy code
                      Type EmployeeRecord    ' Create user-defined type.
    ID As Integer    ' Define elements of data type.
    Name As String * 20
    Address As String * 30
    Phone As Long
    HireDate As Date
End Type
Sub CreateRecord()
    Dim MyRecord As EmployeeRecord    ' Declare variable.

    ' Assignment to EmployeeRecord variable must occur in a procedure.
    MyRecord.ID = 12003    ' Assign a value to an element.
End Sub


Unload Statement

 Copy code hover
[image]

Unload Statement
Send feedback

Removes an object from memory.

Syntax

Unload object

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

Remarks

When an object is unloaded, it's removed from memory and all memory associated with the object is reclaimed. Until it is placed in memory again using the Load statement, a user can't interact with an object, and the object can't be manipulated programmatically.

Example

The following example assumes two UserForms in a program. In UserForm1's Initialize event, UserForm2 is loaded and shown. When the user clicks UserForm2, it is unloaded and UserForm1 appears. When UserForm1 is clicked, it is unloaded in turn.

Copy code Copy code
' This is the Initialize event procedure for UserForm1
Private Sub UserForm_Initialize()
 Load UserForm2
 UserForm2.Show
End Sub
' This is the Click event for UserForm2
Private Sub UserForm_Click()
 Unload UserForm2
End Sub

' This is the Click event for UserForm1
Private Sub UserForm_Click()
 Unload UserForm1
End Sub


While...Wend Statement

 Copy code hover
[image]

While...Wend Statement
Send feedback

Executes a series of statements as long as a given condition is True.

Syntax

While condition
[statements]

Wend

The While...Wend statement syntax has these parts:

Part | Description
condition | Required. Numeric expression or string expression that evaluates to True or False. If condition is Null, condition is treated as False.
statements | Optional. One or more statements executed while condition is True.

Remarks

If condition is True, all statements are executed until the Wend statement is encountered. Control then returns to the While statement and condition is again checked. If condition is still True, the process is repeated. If it is not True, execution resumes with the statement following the Wend statement.

While...Wend loops can be nested to any level. Each Wend matches the most recent While.

Tip Tip

The Do...Loop statement provides a more structured and flexible way to perform looping.

Example

This example uses the While...Wend statement to increment a counter variable. The statements in the loop are executed as long as the condition evaluates to True.

Copy code Copy code
Dim Counter
Counter = 0 ' Initialize variable.
While Counter < 20 ' Test value of Counter.
 Counter = Counter + 1 ' Increment Counter.
Wend ' End While loop when Counter > 19.
Debug.Print Counter ' Prints 20 in the Immediate window.


Width # Statement

 Copy code hover
[image]

Width # Statement
Send feedback

Assigns an output line width to a file opened using the Open statement.

Syntax

Width # filenumber, width

The Width # statement syntax has these parts:

Part | Description
filenumber | Required. Any valid file number.
width | Required. Numeric expression in the range 0-255, inclusive, that indicates how many characters appear on a line before a new line is started. If width equals 0, there is no limit to the length of a line. The default value for width is 0.

Example

This example uses the Width # statement to set the output line width for a file.

Copy code Copy code
Dim I
Open "TESTFILE" For Output As #1 ' Open file for output.
VBA.Width 1, 5 ' Set output line width to 5.
For I = 0 To 9 ' Loop 10 times.
 Print #1, Chr(48 + I); ' Prints five characters per line.
Next I
Close #1 ' Close file.


With Statement

 Copy code hover
[image]

With Statement
Send feedback

Executes a series of statements on a single object or a user-defined type.

Syntax

With object
[statements]

End With

The With statement syntax has these parts:

Part | Description
object | Required. Name of an object or a user-defined type.
statements | Optional. One or more statements to be executed on object.

Remarks

The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object. For example, to change a number of different properties on a single object, place the property assignment statements within the With control structure, referring to the object once instead of referring to it with each property assignment. The following example illustrates use of the With statement to assign values to several properties of the same object.

Copy code Copy code
With MyLabel
 .Height = 2000
 .Width = 2000
 .Caption = "This is MyLabel"
End With
Note Note

Once a With block is entered, object can't be changed. As a result, you can't use a single With statement to affect a number of different objects.

You can nest With statements by placing one With block within another. However, because members of outer With blocks are masked within the inner With blocks, you must provide a fully qualified object reference in an inner With block to any member of an object in an outer With block.

Note Note

In general, it's recommended that you don't jump into or out of With blocks. If statements in a With block are executed, but either the With or End With statement is not executed, a temporary variable containing a reference to the object remains in memory until you exit the procedure.

Example

This example uses the With statement to execute a series of statements on a single object. The object and its properties are generic names used for illustration purposes only.

Copy code Copy code
                      With MyObject
 .Height = 100 ' Same as MyObject.Height = 100.
 .Caption = "Hello World" ' Same as MyObject.Caption = "Hello World".
 With .Font
 .Color = Red ' Same as MyObject.Font.Color = Red.
 .Bold = True ' Same as MyObject.Font.Bold = True.
 End WithEnd With


Write # Statement

 Copy code hover
[image]

Write # Statement
Send feedback

Writes data to a sequential file.

Syntax

Write # filenumber, [outputlist]

The Write # statement syntax has these parts:

Part | Description
filenumber | Required. Any valid file number.
outputlist | Optional. One or more comma-delimited numeric expressions or string expressions to write to a file.

Remarks

Data written with Write # is usually read from a file with Input #.

If you omit outputlist and include a comma after filenumber, a blank line is printed to the file. Multiple expressions can be separated with a space, a semicolon, or a comma. A space has the same effect as a semicolon.

When Write # is used to write data to a file, several universal assumptions are followed so the data can always be read and correctly interpreted using Input #, regardless of locale:

  • Numeric data is always written using the period as the decimal separator.

  • For Boolean data, either #TRUE# or #FALSE# is printed. The True and False keywords are not translated, regardless of locale.

  • Date data is written to the file using the universal date format. When either the date or the time component is missing or zero, only the part provided gets written to the file.

  • Nothing is written to the file if outputlist data is Empty. However, for Null data, #NULL# is written.

  • If outputlist data is Null data, #NULL# is written to the file.

  • For Error data, the output appears as #ERROR errorcode# . The Error keyword is not translated, regardless of locale.

Unlike the Print # statement, the Write # statement inserts commas between items and quotation marks around strings as they are written to the file. You don't have to put explicit delimiters in the list. Write # inserts a newline character, that is, a carriage return-linefeed (Chr(13) + Chr(10)), after it has written the final character in outputlist to the file.

Note Note

You should not write strings that contain embedded quotation marks, for example, "1,2""X" for use with the Input # statement: Input # parses this string as two complete and separate strings.

Example

This example uses the Write # statement to write raw data to a sequential file.

Copy code Copy code
Open "TESTFILE" For Output As #1    ' Open file for output.
Write #1, "Hello World", 234    ' Write comma-delimited data.
Write #1,    ' Write blank line.

Dim MyBool, MyDate, MyNull, MyError
' Assign Boolean, Date, Null, and Error values.
MyBool = False : MyDate = #February 12, 1969# : MyNull = Null
MyError = CVErr(32767)
' Boolean data is written as #TRUE# or #FALSE#. Date literals are
' written in universal date format, for example, #1994-07-13#
 'represents July 13, 1994. Null data is written as #NULL#.
' Error data is written as #ERROR errorcode#.
Write #1, MyBool ; " is a Boolean value"
Write #1, MyDate ; " is a date"
Write #1, MyNull ; " is a null value"
Write #1, MyError ; " is an error value"
Close #1    ' Close file.


Deftype Statements

 Copy code hover
[image]

Deftype Statements
Send feedback

Used at module level to set the default data type for variables, arguments passed to procedures, and the return type for Function and Property Get procedures whose names start with the specified characters.

Syntax

DefBool letterrange[, letterrange] . . .

DefByte letterrange[, letterrange] . . .

DefInt letterrange[, letterrange] . . .

DefLng letterrange[, letterrange] . . .

DefLngLng letterrange[, letterrange] . . . (Valid on 64-bit platforms only.)

DefLngPtr letterrange[, letterrange] . . .

DefCur letterrange[, letterrange] . . .

DefSng letterrange[, letterrange] . . .

DefDbl letterrange[, letterrange] . . .

DefDec letterrange[, letterrange] . . .

DefDate letterrange[, letterrange] . . .

DefStr letterrange[, letterrange] . . .

DefObj letterrange[, letterrange] . . .

DefVar letterrange[, letterrange] . . .

The required letterrange argument has the following syntax:

letter1[-letter2]

The letter1 and letter2 arguments specify the name range for which you can set a default data type. Each argument represents the first letter of the variable, argument, Function procedure, or Property Get procedure name and can be any letter of the alphabet. The case of letters in letterrange isn't significant.

Remarks

The statement name determines the data type:

Statement | Data Type
DefBool | Boolean
DefByte | Byte
DefInt | Integer
DefLng | Long
DefLngLng | LongLong (Valid on 64-bit platforms only.)
DefLngPtr | LongPtr
DefCur | Currency
DefSng | Single
DefDbl | Double
DefDec | Decimal (not currently supported)
DefDate | Date
DefStr | String
DefObj | Object
DefVar | Variant

For example, in the following program fragment, is a string variable:

A Def type statement affects only the module where it is used. For example, a DefInt statement in one module affects only the default data type of variables, arguments passed to procedures, and the return type for Function and Property Get procedures declared in that module; the default data type of variables, arguments, and return types in other modules is unaffected. If not explicitly declared with a Def type statement, the default data type for all variables, all arguments, all Function procedures, and all Property Get procedures is Variant.

When you specify a letter range, it usually defines the data type for variables that begin with letters in the first 128 characters of the character set. However, when you specify the letter range A-Z, you set the default to the specified data type for all variables, including variables that begin with international characters from the extended part of the character set (128-255).

Once the range A-Z has been specified, you can't further redefine any subranges of variables using Def type statements. Once a range has been specified, if you include a previously defined letter in another Def type statement, an error occurs. However, you can explicitly specify the data type of any variable, defined or not, using a Dim statement with an As type clause. For example, you can use the following code at module level to define a variable as a Double even though the default data type is Integer:

Def type statements don't affect elements of user-defined types because the elements must be explicitly declared.

Example

This example shows various uses of the Def type statements to set default data types of variables and function procedures whose names start with specified characters. The default data type can be overridden only by explicit assignment using the Dim statement. Def type statements can only be used at the module level (that is, not within procedures).


Strings

 Copy code hover
[image]

Strings
Send feedback

In this section

  • Returns for CStr


Returns for CStr

 Copy code hover
[image]

Returns for CStr
Send feedback
If expression is | CStr returns
Boolean | A string containing True or False
Date | A string containing a date in the short date format of your system
Null | A run-time error
Empty | A zero-length string ("")
Error | A string containing the word Error followed by the error number
Other numeric | A string containing the number


Visual Basic add-in model reference

 Copy code hover
[image]

Visual Basic add-in model reference
Send feedback

In this section

  • Collections (Visual Basic Add-In Model)

  • Events (Visual Basic Add-In Model)

  • Methods (Visual Basic Add-In Model)

  • Objects (Visual Basic Add-In Model)

  • Properties (Visual Basic Add-In Model)


Collections (Visual Basic Add-In Model)

 Copy code hover
[image]

Collections (Visual Basic Add-In Model)
Send feedback

In this section

  • AddIns Collection (VBA Add-In Object Model)

  • CodePanes Collection (VBA Add-In Object Model)

  • CommandBars Collection (VBA Add-In Object Model)

  • LinkedWindows Collection (VBA Add-In Object Model)

  • Properties Collection (VBA Add-In Object Model)

  • References Collection (VBA Add-In Object Model)

  • VBComponents Collection (VBA Add-In Object Model)

  • VBNewProjects Collection (VBA Add-In Object Model)

  • VBProjects Collection (VBA Add-In Object Model)

  • Windows Collection (VBA Add-In Object Model)


AddIns Collection (VBA Add-In Object Model)

 Copy code hover
[image]

AddIns Collection (VBA Add-In Object Model)
Send feedback

Returns a collection of add-ins registered for VBA.

Syntax

object .AddIns

Remarks

The AddIns collection is accessed through the VBE object. Every add-in listed in the Add-In Manager in VBE.has an object in the AddIns collection.


CodePanes Collection (VBA Add-In Object Model)

 Copy code hover
[image]

CodePanes Collection (VBA Add-In Object Model)
Send feedback

Contains the active code panes in the VBE object.

Remarks

Use the CodePanes collection to access the open code panes in a project.

You can use the Count property to return the number of active code panes in a collection.


CommandBars Collection (VBA Add-In Object Model)

 Copy code hover
[image]

CommandBars Collection (VBA Add-In Object Model)
Send feedback

Contains all of the command bars in a project, including command bars that support shortcut menus.

Remarks

Use the CommandBars collection to enable add-ins to add command bars and controls, or to add controls to existing, built-in, command bars.


LinkedWindows Collection (VBA Add-In Object Model)

 Copy code hover
[image]

LinkedWindows Collection (VBA Add-In Object Model)
Send feedback

Contains all linked windows in a linked window frame.

Remarks

Use the LinkedWindows collection to modify the docked and linked state of windows in the development environment.

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements will generate run-time errors when run on the Macintosh.

The LinkedWindowFrame property of the Window object returns a Window object that has a valid LinkedWindows collection.

Linked window frames contain all windows that can be linked or docked. This includes all windows except code windows, designers, the Object Browser window, and the Search and Replace window.

If all the panes from one linked window frame are moved to another window, the linked window frame with no panes is destroyed. However, if all the panes are removed from the main window, it isn't destroyed.

Use the Visible property to check or set the visibility of a window.

You can use the Add method to add a window to the collection of currently linked windows. A window that is a pane in one linked window frame can be added to another linked window frame. Use the Remove method to remove a window from the collection of currently linked windows; this results in the window being unlinked or undocked.

The LinkedWindows collection is used to dock and undock windows from the main window frame.


Properties Collection (VBA Add-In Object Model)

 Copy code hover
[image]

Properties Collection (VBA Add-In Object Model)
Send feedback

Represents the properties of an object.

Remarks

Use the Properties collection to access the properties displayed in the Properties window. For every property listed in the Properties window, there is an object in the Properties collection.


References Collection (VBA Add-In Object Model)

 Copy code hover
[image]

References Collection (VBA Add-In Object Model)
Send feedback

Represents the set of references in the project.

Remarks

Use the References collection to add or remove references. The References collection is the same as the set of references selected in the References dialog box.


VBComponents Collection (VBA Add-In Object Model)

 Copy code hover
[image]

VBComponents Collection (VBA Add-In Object Model)
Send feedback

Represents the components contained in a project.

Remarks

Use the VBComponents collection to access, add, or remove components in a project. A component can be a form, module, or class. The VBComponents collection is a standard collection that can be used in a ForEach block.

You can use the Parent property to return the project the VBComponents collection is in.

In Visual Basic for Applications, you can use Import method to add a component to a project from a file.


VBNewProjects Collection (VBA Add-In Object Model)

 Copy code hover
[image]

VBNewProjects Collection (VBA Add-In Object Model)
Send feedback

Represents all of the new projects in the development environment.

Remarks

Use the VBNewProjects collection to access specific projects in an instance of the development environment. VBNewProjects is a standard collection that you can iterate through using a For… Each block.


VBProjects Collection (VBA Add-In Object Model)

 Copy code hover
[image]

VBProjects Collection (VBA Add-In Object Model)
Send feedback

Represents all the projects that are open in the development environment.

Remarks

Use the VBProjects collection to access specific projects in an instance of the development environment. VBProjects is a standard collection that can be used in a ForEach block.


Windows Collection (VBA Add-In Object Model)

 Copy code hover
[image]

Windows Collection (VBA Add-In Object Model)
Send feedback

Contains all open or permanent windows.

Remarks

Use the Windows collection to access Window objects.

The Windows collection has a fixed set of windows that are always available in the collection, such as the Project window, the Properties window, and a set of windows that represent all open code windows and designer windows. Opening a code or designer window adds a new member to the Windows collection. Closing a code or designer window removes a member from the Windows collection. Closing a permanent development environment window doesn't remove the corresponding object from this collection, but results in the window not being visible.


Events (Visual Basic Add-In Model)

 Copy code hover
[image]

Events (Visual Basic Add-In Model)
Send feedback

In this section

  • Click Event (VBA Add-In Object Model)

  • ItemAdded Event (VBA Add-In Object Model)

  • ItemRemoved Event (VBA Add-In Object Model)


Click Event (VBA Add-In Object Model)

 Copy code hover
[image]

Click Event (VBA Add-In Object Model)
Send feedback

Occurs when the OnAction property of a corresponding command bar control is set.

Syntax

Sub object _Click (ByVal ctrl As Object, ByRef handled As Boolean, ByRef canceldefault As Boolean)

The Click event syntax has these named arguments:

Part | Description
ctrl | Required; Object. Specifies the object that is the source of the Click event.
handled | Required; Boolean. If True, other add-ins should handle the event. If False, the action of the command bar item has not been handled.
canceldefault | Required; Boolean. If True, default behavior is performed unless canceled by a downstream add-in. If False, default behavior is not performed unless restored by a downstream add-in.

Remarks

The Click event is specific to the CommandBarEvents object. Use a variable declared using the WithEvents keyword to receive the Click event for a CommandBar control. This variable should be set to the return value of the CommandBarEvents property of the Events object. The CommandBarEvents property takes the CommandBar control as an argument. When the CommandBar control is clicked (for the variable you declared using the WithEvents keyword), the code is executed.


ItemAdded Event (VBA Add-In Object Model)

 Copy code hover
[image]

ItemAdded Event (VBA Add-In Object Model)
Send feedback

Occurs after a reference is added.

Syntax

Sub object _ItemAdded(ByVal item As Reference)

The required item argument specifies the item that was added.

Remarks

The ItemAdded event occurs when a Reference is added to the References collection.


ItemRemoved Event (VBA Add-In Object Model)

 Copy code hover
[image]

ItemRemoved Event (VBA Add-In Object Model)
Send feedback

Occurs after a reference is removed from a project.

Syntax

Sub object _ItemRemoved(ByVal item As Reference)

The required item argument specifies the Reference that was removed.


Methods (Visual Basic Add-In Model)

 Copy code hover
[image]

Methods (Visual Basic Add-In Model)
Send feedback

In this section

  • Add Method (VBA Add-In Object Model)

  • AddCustom Method

  • AddFromFile Method (VBA Add-In Object Model)

  • AddFromGuid Method (VBA Add-In Object Model)

  • AddFromString Method (VBA Add-In Object Model)

  • Close Method (VBA Add-In Object Model)

  • CreateEventProc Method (VBA Add-In Object Model)

  • CreateToolWindow Method

  • DeleteLines Method (VBA Add-In Object Model)

  • DesignerWindow Method

  • Export Method (VBA Add-In Object Model)

  • Find Method (VBA Add-In Object Model)

  • GetSelection Method (VBA Add-In Object Model)

  • Import Method (VBA Add-In Object Model)

  • InsertFile Method

  • InsertLines Method (VBA Add-In Object Model)

  • Item Method (VBA Add-In Object Model)

  • MakeCompiledFile Method

  • Remove Method (VBA Add-In Object Model)

  • ReplaceLine Method (VBA Add-In Object Model)

  • SaveAs Method (VBA Add-In Object Model)

  • SetFocus Method (VBA Add-In Object Model)

  • SetSelection Method (VBA Add-In Object Model)

  • Show Method (VBA Add-In Object Model)

  • Update Method (VBA Add-In Object Model)


Add Method (VBA Add-In Object Model)

 Copy code hover
[image]

Add Method (VBA Add-In Object Model)
Send feedback

Adds an object to a collection.

Syntax

object .Add( component )

The Add syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
component | Required. For the LinkedWindows collection, an object. For the VBComponents collection, an enumerated constant representing a class module, a form, or a standard module. For the VBProjects collection, an enumerated constant representing a project type.

You can use one of the following constants for the component argument:

Constant | Description
vbext_ct_ClassModule | Adds a class module to the collection.
vbext_ct_MSForm | Adds a form to the collection.
vbext_ct_StdModule | Adds a standard module to the collection.
vbext_pt_StandAlone | Adds a standalone project to the collection.

Remarks

For the LinkedWindows collection, the Add method adds a window to the collection of currently linked windows.

Note Note

You can add a window that is a pane in one linked window frame to another linked window frame; the window is simply moved from one pane to the other. If the linked window frame that the window was moved from no longer contains any panes, it's destroyed.

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements generate run-time errors when run on the Macintosh.

For the VBComponents collection, the Add method creates a new standard component and adds it to the project.

For the VBComponents collection, the Add method returns a VBComponent object. For the LinkedWindows collection, the Add method returns Nothing.

For the VBProjects collection, the Add method returns a VBProject object and adds a project to the VBProjects collection.


AddCustom Method

 Copy code hover
[image]

AddCustom Method
Send feedback

Returns a VBComponent object, or creates a new custom component and adds it to the project.

Syntax

object .AddCustom (ByVal progid As String) As VBComponent

The AddCustom method syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
progid | Required. The ProgID of the custom component to be created.


AddFromFile Method (VBA Add-In Object Model)

 Copy code hover
[image]

AddFromFile Method (VBA Add-In Object Model)
Send feedback

For the References collection, adds a reference to a project from a file. For the CodeModule object, adds the contents of a file to a module.

Syntax

object .AddFromFile( filename )

The AddFromFile syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
filename | Required. A string expression specifying the name of the file you want to add to the project or module. If the file name isn't found and a path name isn't specified, the directories searched by the Windows OpenFile function are searched.

Remarks

For the CodeModule object, the AddFromFile method inserts the contents of the file starting on the line preceding the first procedure in the code module. If the module doesn't contain procedures, AddFromFile places the contents of the file at the end of the module.


AddFromGuid Method (VBA Add-In Object Model)

 Copy code hover
[image]

AddFromGuid Method (VBA Add-In Object Model)
Send feedback

Adds a reference to the References collection using the globally unique identifier (GUID) of the reference.

Syntax

object .AddFromGuid( guid, major, minor) As Reference

The AddFromGuid syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
guid | Required. A string expressionrepresenting the GUID of the reference.
major | Required. A Long specifying the major version number of the reference.
minor | Required. A Long specifying the minor version number of the reference.

Remarks

The AddFromGuid method searches the registry to find the reference you want to add. The GUID can be a type library, control, class identifier, and so on.


AddFromString Method (VBA Add-In Object Model)

 Copy code hover
[image]

AddFromString Method (VBA Add-In Object Model)
Send feedback

Adds text to a module.

Syntax

object .AddFromString

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

Remarks

The AddFromString method inserts the text starting on the line preceding the first procedure in the module. If the module doesn't contain procedures, AddFromString places the text at the end of the module.


Close Method (VBA Add-In Object Model)

 Copy code hover
[image]

Close Method (VBA Add-In Object Model)
Send feedback

Closes and destroys a window.

Syntax

object .Close

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

Remarks

The following types of windows respond to the Close method in different ways:

  • For a window that is a code pane, Close destroys the code pane.

  • For a window that is a designer, Close destroys the contained designer.

  • For windows that are always available on the View menu, Close hides the window.


CreateEventProc Method (VBA Add-In Object Model)

 Copy code hover
[image]

CreateEventProc Method (VBA Add-In Object Model)
Send feedback

Creates an event procedure.

Syntax

object .CreateEventProc( eventname, objectname) As Long

The CreateEventProc syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
eventname | Required. A string expression specifying the name of the event you want to add to the module.
objectname | Required. A string expression specifying the name of the object that is the source of the event.

Remarks

Use the CreateEventProc method to create an event procedure. For example, to create an event procedure for the Click event of a Command Button control named Command1 you would use the following code, where CM represents an object of type CodeModule:

VBA Copy code Copy code
TextLocation = CM.CreateEventProc("Click", "Command1")

The CreateEventProc method returns the line at which the body of the event procedure starts. CreateEventProc fails if the arguments refer to a nonexistent event.


CreateToolWindow Method

 Copy code hover
[image]

CreateToolWindow Method
Send feedback

Creates a new Tool window containing the indicated UserDocument object.

Syntax

object.CreateToolWindow (AddInInst, ProgID, Caption, GuidPosition, DocObj) As Window

The CreateToolWindow method syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
AddInInst | Required. An add-in instance variable representing an add-in in the development environment.
ProgID | Required. String representing the progID of the UserDocument object.
Caption | Required. String containing the window caption.
GuidPosition | Required. String containing a unique identifier for the window.
DocObj | Required. Object representing a UserDocument object. This object will be set in the call to this function.


DeleteLines Method (VBA Add-In Object Model)

 Copy code hover
[image]

DeleteLines Method (VBA Add-In Object Model)
Send feedback

Deletes a single line or a specified range of lines.

Syntax

object .DeleteLines ( startline [, count])

The DeleteLines syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
startline | Required. A Long specifying the first line you want to delete.
count | Optional. A Long specifying the number of lines you want to delete.

Remarks

If you don't specify how many lines you want to delete, DeleteLines deletes one line.


DesignerWindow Method

 Copy code hover
[image]

DesignerWindow Method
Send feedback

Returns the Window object that represents the component's designer.

Syntax

object .DesignerWindow

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

Remarks

If the component supports a designer but doesn't have an open designer, using the DesignerWindow method creates the designer, but it isn't visible. To make the window visible, set the Window object's Visible property to True.


Export Method (VBA Add-In Object Model)

 Copy code hover
[image]

Export Method (VBA Add-In Object Model)
Send feedback

Saves a component as a separate file or files.

Syntax

object .Export( filename )

The Export syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
filename | Required. A String specifying the name of the file that you want to export the component to.

Remarks

When you use the Export method to save a component as a separate file or files, use a file name that doesn't already exist; otherwise, an error occurs.


Find Method (VBA Add-In Object Model)

 Copy code hover
[image]

Find Method (VBA Add-In Object Model)
Send feedback

Searches the active module for a specified string.

Syntax

object .Find( target, startline, startcol, endline, endcol [, wholeword] [, matchcase] [, patternsearch]) As Boolean

The Find syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
target | Required. A String containing the text or pattern you want to find.
startline | Required. A Long specifying the line at which you want to start the search; will be set to the line of the match if one is found. The first line is number 1.
startcol | Required. A Long specifying the column at which you want to start the search; will be set to the column containing the match if one is found. The first column is 1.
endline | Required. A Long specifying the last line of the match if one is found. The last line may be specified as -1.
endcol | Required. A Long specifying the last line of the match if one is found. The last column may be designated as -1.
wholeword | Optional. A Boolean value specifying whether to only match whole words. If True, only matches whole words. False is the default.
matchcase | Optional. A Boolean value specifying whether to match case. If True, the search is case sensitive. False is the default.
patternsearch | Optional. A Boolean value specifying whether or not the target string is a regular expression pattern. If True, the target string is a regular expression pattern. False is the default.

Remarks

Find returns True if a match is found and False if a match isn't found.

The matchcase and patternsearch arguments are mutually exclusive; if both arguments are passed as True, an error occurs.

The content of the Find dialog box isn't affected by the Find method.

The specified range of lines and columns is inclusive, so a search can find the pattern on the specified last line if endcol is supplied as either -1 or the length of the line.


GetSelection Method (VBA Add-In Object Model)

 Copy code hover
[image]

GetSelection Method (VBA Add-In Object Model)
Send feedback

Returns the selection in a code pane.

Syntax

object .GetSelection( startline, startcol, endline, endcol)

The GetSelection syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
startline | Required. A Long that returns a value specifying the first line of the selection in the code pane.
startcol | Required. A Long that returns a value specifying the first column of the selection in the code pane.
endline | Required. A Long that returns a value specifying the last line of the selection in the code pane.
endcol | Required. A Long that returns a value specifying the last column of the selection in the code pane.

Remarks

When you use the GetSelection method, information is returned in output arguments. As a result, you must pass in variables because the variables will be modified to contain the information when returned.


Import Method (VBA Add-In Object Model)

 Copy code hover
[image]

Import Method (VBA Add-In Object Model)
Send feedback

Adds a component to a project from a file; returns the newly added component.

Syntax

object .Import( filename ) As VBComponent

The Import syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
filename | Required. A String specifying path and file name of the component that you want to import the component from.

Remarks

You can use the Import method to add a component, form, module, class, and so on, to your project.


InsertFile Method

 Copy code hover
[image]

InsertFile Method
Send feedback

Inserts code from a file into a code module.

object .InsertFile( filename ) As String

The InsertFile syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
filename | Required. A String specifying the file containing the code to insert into the code module.


InsertLines Method (VBA Add-In Object Model)

 Copy code hover
[image]

InsertLines Method (VBA Add-In Object Model)
Send feedback

Inserts a line or lines of code at a specified location in a block of code.

Syntax

object .InsertLines( line, code)

The InsertLines syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
line | Required. A Long specifying the location at which you want to insert the code.
code | Required. A String containing the code you want to insert.

Remarks

If the text you insert using the InsertLines method is carriage return-linefeed delimited, it will be inserted as consecutive lines.


Item Method (VBA Add-In Object Model)

 Copy code hover
[image]

Item Method (VBA Add-In Object Model)
Send feedback

Returns the indexed member of a collection.

Syntax

object .Item( index )

The Item method syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
index | Required. An expression that specifies the position of a member of the collection. If a numeric expression, index must be a number from 1 to the value of the collection's Count property. If a string expression, index must correspond to the key argument specified when the member was added to the collection.

The following table lists the collections and their corresponding key arguments for use with the Item method. The string you pass to the Item method must match the collection's key argument.

Collection | Key argument
Windows | Caption property setting
LinkedWindows | Caption property setting
CodePanes | No unique string is associated with this collection.
VBProjects | Name property setting
VBComponents | Name property setting
References | Name property setting
Properties | Name property setting

Remarks

The index argument can be a numeric value or a string containing the title of the object.

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements will generate run-time errors when run on the Macintosh.


MakeCompiledFile Method

 Copy code hover
[image]

MakeCompiledFile Method
Send feedback

Causes the current project to be written as a DLL. The DLL name is specified by the BuildFileName property.

Syntax

object.MakeCompiledFile

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


Remove Method (VBA Add-In Object Model)

 Copy code hover
[image]

Remove Method (VBA Add-In Object Model)
Send feedback

Removes an item from a collection.

Syntax

object .Remove( component )

The Remove syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
component | Required. For the LinkedWindows collection, an object. For the References collection, a reference to a type library or a project. For the VBComponents collection, an enumerated constant representing a class module, a form, or a standard module. For the VBProjects collection, a standalone project.

Remarks

When used on the LinkedWindows collection, the Remove method removes a window from the collection of currently linked windows. The removed window becomes a floating window that has its own linked window frame. The Remove method can only be used on a standalone project. It generates a run-time error if you try to use it on a host project.

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements generate run-time errors when run on the Macintosh.


ReplaceLine Method (VBA Add-In Object Model)

 Copy code hover
[image]

ReplaceLine Method (VBA Add-In Object Model)
Send feedback

Replaces an existing line of code with a specified line of code.

Syntax

object .ReplaceLine( line, code)

The ReplaceLine syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
line | Required. A Long specifying the location of the line you want to replace.
code | Required. A String containing the code you want to insert.


SaveAs Method (VBA Add-In Object Model)

 Copy code hover
[image]

SaveAs Method (VBA Add-In Object Model)
Send feedback

Saves a project to a given location using a new filename.

Syntax

object .SaveAs ( newfilename As String)

The SaveAs method syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
newfilename | Required. A string expression specifying the new filename for the component to be saved.

Remarks

If a new path name is given, it is used. Otherwise, the old path name is used. If the new filename is invalid or refers to a read-only file, an error occurs.

The SaveAs method can only be used on standalone projects. It generates a run-time error if you use it with a host project.


SetFocus Method (VBA Add-In Object Model)

 Copy code hover
[image]

SetFocus Method (VBA Add-In Object Model)
Send feedback

Moves the focus to the specified window.

Syntax

object .SetFocus

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

Remarks

Use the SetFocus method on windows that are already visible.


SetSelection Method (VBA Add-In Object Model)

 Copy code hover
[image]

SetSelection Method (VBA Add-In Object Model)
Send feedback

Sets the selection in the code pane.

Syntax

object .SetSelection( startline, startcol, endline, endcol)

The SetSelection syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
startline | Required. A Long specifying the first line of the selection.
startcol | Required. A Long specifying the first column of the selection.
endline | Required. A Long specifying the last line of the selection.
endcol | Required. A Long specifying the last column of the selection.


Show Method (VBA Add-In Object Model)

 Copy code hover
[image]

Show Method (VBA Add-In Object Model)
Send feedback

Makes the specified code pane the visible code pane in its window.

Syntax

object .Show

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

Remarks

The Show method makes the specified code pane the pane with the focus in its window.


Update Method (VBA Add-In Object Model)

 Copy code hover
[image]

Update Method (VBA Add-In Object Model)
Send feedback

Refreshes the contents of the AddIns collection from the add-ins listed in the Vbaddin.ini file in the same manner as if the user had opened the Add-In Manager dialog box.

Syntax

object.Update

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

Remarks

All add-ins listed in the Vbaddin.ini file must be registered ActiveX components in the Registry before they can be used in Visual Basic.


Objects (Visual Basic Add-In Model)

 Copy code hover
[image]

Objects (Visual Basic Add-In Model)
Send feedback

In this section

  • AddIn Object

  • CodeModule Object (VBA Add-In Object Model)

  • CodePane Object (VBA Add-In Object Model)

  • CommandBar Object

  • CommandBarEvents Object (VBA Add-In Object Model)

  • Events Object (VBA Add-In Object Model)

  • Property Object (VBA Add-In Object Model)

  • Reference Object (VBA Add-In Object Model)

  • ReferencesEvents Object (VBA Add-In Object Model)

  • VBComponent Object (VBA Add-In Object Model)

  • VBE Object (VBA Add-In Object Model)

  • VBProject Object (VBA Add-In Object Model)

  • Window Object (VBA Add-In Object Model)


AddIn Object

 Copy code hover
[image]

AddIn Object
Send feedback

The AddIn object provides information about an add-in to other add-ins.

Syntax

object .AddIn

Remarks

An AddIn object is created for every add-in that appears in the Add-In Manger.


CodeModule Object (VBA Add-In Object Model)

 Copy code hover
[image]

CodeModule Object (VBA Add-In Object Model)
Send feedback

Represents the code behind a component, such as a form, class, or document.

Remarks

You use the CodeModule object to modify (add, delete, or edit) the code associated with a component.

Each component is associated with one CodeModule object. However, a CodeModule object can be associated with multiple code panes.

The methods associated with the CodeModule object enable you to manipulate and return information about the code text on a line-by-line basis. For example, you can use the AddFromString method to add text to the module. AddFromString places the text just above the first procedure in the module or places the text at the end of the module if there are no procedures.

Use the Parent property to return the VBComponent object associated with a code module.


CodePane Object (VBA Add-In Object Model)

 Copy code hover
[image]

CodePane Object (VBA Add-In Object Model)
Send feedback

Represents a code pane.

Remarks

Use the CodePane object to manipulate the position of visible text or the text selection displayed in the code pane.

You can use the Show method to make the code pane you specify visible. Use the SetSelection method to set the selection in a code pane and the GetSelection method to return the location of the selection in a code pane.


CommandBar Object

 Copy code hover
[image]

CommandBar Object
Send feedback

The CommandBar object contains other CommandBar objects, which can act as either buttons or menu commands.

Syntax

CommandBar


CommandBarEvents Object (VBA Add-In Object Model)

 Copy code hover
[image]

CommandBarEvents Object (VBA Add-In Object Model)
Send feedback

Returned by the CommandBarEvents property. The CommandBarEvents object triggers an event when a control on the command bar is clicked.

Remarks

The CommandBarEvents object is returned by the CommandBarEvents property of the Events object. The object that is returned has one event in its interface, the Click event. You can handle this event using the WithEvents object declaration.


Events Object (VBA Add-In Object Model)

 Copy code hover
[image]

Events Object (VBA Add-In Object Model)
Send feedback

Supplies properties that enable add-ins to connect to all events in Visual Basic for Applications.

Remarks

The Events object provides properties that return event source objects. Use the properties to return event source objects that notify you of changes in the Visual Basic for Applications environment.

The properties of the Events object return objects of the same type as the property name. For example, the CommandBarEvents property returns the CommandBarEvents object.


Property Object (VBA Add-In Object Model)

 Copy code hover
[image]

Property Object (VBA Add-In Object Model)
Send feedback

Represents the properties of an object that are visible in the Properties window for any given component.

Remarks

Use Value property of the Property object to return or set the value of a property of a component.

At a minimum, all components have a Name property. Use the Value property of the Property object to return or set the value of a property. The Value property returns a Variant of the appropriate type. If the value returned is an object, the Value property returns the Properties collection that contains Property objects representing the individual properties of the object. You can access each of the Property objects by using the Item method on the returned Properties collection.

If the value returned by the Property object is an object, you can use the Object property to set the Property object to a new object.


Reference Object (VBA Add-In Object Model)

 Copy code hover
[image]

Reference Object (VBA Add-In Object Model)
Send feedback

Represents a reference to a type library or a project.

Remarks

Use the Reference object to verify whether a reference is still valid.

The IsBroken property returns True if the reference no longer points to a valid reference. The BuiltIn property returns True if the reference is a default reference that can't be moved or removed. Use the Name property to determine if the reference you want to add or remove is the correct one.


ReferencesEvents Object (VBA Add-In Object Model)

 Copy code hover
[image]

ReferencesEvents Object (VBA Add-In Object Model)
Send feedback

Returned by the ReferencesEvents property.

Remarks

The ReferencesEvents object is the source of events that occur when a reference is added to or removed from a project. The ItemAdded event is triggered after a reference is added to a project. The ItemRemoved event is triggered after a reference is removed from a project.


VBComponent Object (VBA Add-In Object Model)

 Copy code hover
[image]

VBComponent Object (VBA Add-In Object Model)
Send feedback

Represents a component, such as a class module or standard module, contained in a project.

Remarks

Use the VBComponent object to access the code module associated with a component or to change a component's property settings.

You can use the Type property to find out what type of component the VBComponent object refers to. Use the Collection property to find out what collection the component is in.


VBE Object (VBA Add-In Object Model)

 Copy code hover
[image]

VBE Object (VBA Add-In Object Model)
Send feedback

The root object that contains all other objects and collections represented in Visual Basic for Applications.

Remarks

You can use the following collections to access the objects contained in the VBE object:

  • Use the VBProjects collection to access the collection of projects.

  • Use the AddIns collection to access the collection of add-ins.

  • Use the Windows collection to access the collection of windows.

  • Use the CodePanes collection to access the collection of code panes.

  • Use the CommandBars collection to access the collection of command bars.

Use the Events object to access properties that enable add-ins to connect to all events in Visual Basic for Applications. The properties of the Events object return objects of the same type as the property name. For example, the CommandBarEvents property returns the CommandBarEvents object.

You can use the SelectedVBComponent property to return the active component. The active component is the component that is being tracked in the Project window. If the selected item in the Project window isn't a component, SelectedVBComponent returns Nothing.

Note Note

All objects in this object model have a VBE property that points to the VBE object.


VBProject Object (VBA Add-In Object Model)

 Copy code hover
[image]

VBProject Object (VBA Add-In Object Model)
Send feedback

Represents a project.

Remarks

Use the VBProject object to set properties for the project, to access the VBComponents collection, and to access the References collection.


Window Object (VBA Add-In Object Model)

 Copy code hover
[image]

Window Object (VBA Add-In Object Model)
Send feedback

Represents a window in the development environment.

Remarks

Use the Window object to show, hide, or position windows.

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements will generate run-time errors when run on the Macintosh.

You can use the Close method to close a window in the Windows collection. The Close method affects different types of windows as follows:

Window | Result of using Close method
Code window | Removes the window from the Windows collection.
Designer | Removes the window from the Windows collection.
Window objects of type linked window frame | Windows become unlinked separate windows.
Note Note

Using the Close method with code windows and designers actually closes the window. Setting the Visible property to False hides the window but doesn't close the window. Using the Close method with development environment windows, such as the Project window or Properties window, is the same as setting the Visible property to False.

You can use the SetFocus method to move the focus to a window.

You can use the Visible property to return or set the visibility of a window.

To find out what type of window you are working with, you can use the Type property. If you have more than one window of a type, for example, multiple designers, you can use the Caption property to determine the window you're working with. You can also find the window you want to work with using the DesignerWindow property of the VBComponent object or the Window property of the CodePane object.


Properties (Visual Basic Add-In Model)

 Copy code hover
[image]

Properties (Visual Basic Add-In Model)
Send feedback

In this section

  • ActiveCodePane Property (VBA Add-In Object Model)

  • ActiveVBProject Property (VBA Add-In Object Model)

  • ActiveWindow Property (VBA Add-In Object Model)

  • AddIns Property

  • BuildFileName Property

  • BuiltIn Property (VBA Add-In Object Model)

  • CodePane Property

  • Caption Property (VBA Add-In Object Model)

  • CodeModule Property (VBA Add-In Object Model)

  • CommandBars Property (VBA Add-In Object Model)

  • CodePanes Property (VBA Add-In Object Model)

  • CodePaneView Property (VBA Add-In Object Model)

  • Connect Property

  • Collection Property (VBA Add-In Object Model)

  • CommandBarEvents Property (VBA Add-In Object Model)

  • Count Property (VBA Add-In Object Model)

  • CountOfDeclarationLines Property (VBA Add-In Object Model)

  • CountOfLines Property (VBA Add-In Object Model)

  • CountOfVisibleLines Property (VBA Add-In Object Model)

  • Description Property (VBA Add-In Object Model)

  • DesignerID Property

  • Designer Property (VBA Add-In Object Model)

  • Events Property

  • FileName Property

  • FullPath Property (VBA Add-In Object Model)

  • GUID Property (VBA Add-In Object Model)

  • HasOpenDesigner Property (VBA Add-In Object Model)

  • Height Property (VBA Add-In Object Model)

  • HelpContextID Property (VBA Add-In Object Model)

  • HelpFile Property (VBA Add-In Object Model)

  • IndexedValue Property (VBA Add-In Object Model)

  • IsBroken Property (VBA Add-In Object Model)

  • Left Property (VBA Add-In Object Model)

  • Lines Property

  • LinkedWindowFrame Property (VBA Add-In Object Model)

  • LinkedWindows Property

  • MainWindow Property (VBA Add-In Object Model)

  • Major Property (VBA Add-In Object Model)

  • Minor Property (VBA Add-In Object Model)

  • Mode Property (VBA Add-In Object Model)

  • Name Property (VBA Add-In Object Model)

  • NumIndices Property (VBA Add-In Object Model)

  • Object Property (VBA Add-In Object Model)

  • Parent Property (VBA Add-In Object Model)

  • ProcBodyLine Property

  • ProcCountLines Property

  • ProcOfLine Property

  • ProcStartLine Property

  • ProgID Property

  • Protection Property (VBA Add-In Object Model)

  • ReferencesEvents Property (VBA Add-In Object Model)

  • Saved Property (VBA Add-In Object Model)

  • SelectedVBComponent Property (VBA Add-In Object Model)

  • Top Property (VBA Add-In Object Model)

  • TopLine Property (VBA Add-In Object Model)

  • Type Property (VBA Add-In Object Model)

  • Value Property (VBA Add-In Object Model)

  • VBE Property (VBA Add-In Object Model)

  • VBProjects Property

  • Version Property (VBA Add-In Object Model)

  • Visible Property (VBA Add-In Object Model)

  • Width Property (VBA Add-In Object Model)

  • Window Property (VBA Add-In Object Model)

  • Windows Property

  • WindowState Property (VBA Add-In Object Model)

  • Properties Property (VBA Add-In Object Model)

  • References Property


ActiveCodePane Property (VBA Add-In Object Model)

 Copy code hover
[image]

ActiveCodePane Property (VBA Add-In Object Model)
Send feedback

Returns the active or last active CodePane object or sets the active CodePane object. Read/write.

Remarks

You can set the ActiveCodePane property to any valid CodePane object, as shown in the following example:

VBA Copy code Copy code
Set MyApp.VBE. ActiveCodePane = MyApp.VBE.CodePanes(1)

The preceding example sets the first code pane in a collection of code panes to be the active code pane. You can also activate a code pane using the Set method.


ActiveVBProject Property (VBA Add-In Object Model)

 Copy code hover
[image]

ActiveVBProject Property (VBA Add-In Object Model)
Send feedback

Returns the active project in the Project window. Read-only.

Remarks

The ActiveVBProject property returns the project that is selected in the Project window or the project in which the components are selected. In the latter case, the project itself isn't necessarily selected. Whether or not the project is explicitly selected, there is always an active project.


ActiveWindow Property (VBA Add-In Object Model)

 Copy code hover
[image]

ActiveWindow Property (VBA Add-In Object Model)
Send feedback

Returns the active window in the development environment. Read-only.

Remarks

When more than one window is open in the development environment, the ActiveWindow property setting is the window with the focus. If the main window has the focus, ActiveWindow returns Nothing.


AddIns Property

 Copy code hover
[image]

AddIns Property
Send feedback

Returns a collection which add-ins can use to register their automation components into the extensibility object model.

Syntax

object.AddIns

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


BuildFileName Property

 Copy code hover
[image]

BuildFileName Property
Send feedback

Sets or returns the DLL name that will be used when the project is built.

Syntax

object .BuildFileName

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


BuiltIn Property (VBA Add-In Object Model)

 Copy code hover
[image]

BuiltIn Property (VBA Add-In Object Model)
Send feedback

Returns a Boolean value indicating whether or not the reference is a default reference that can't be removed. Read-only.

Return Values

The BuiltIn property returns these values:

Value | Description
True | The reference is a default reference that can't be removed.
False | The reference isn't a default reference; it can be removed.


CodePane Property

 Copy code hover
[image]

CodePane Property
Send feedback

Returns a CodePane object. Read-only.

Remarks

If a code pane exists, it becomes the active code pane, and the window that contains it becomes the active window. If a code pane doesn't exist for the module, the CodePane property creates one.


Caption Property (VBA Add-In Object Model)

 Copy code hover
[image]

Caption Property (VBA Add-In Object Model)
Send feedback

Returns a String containing the title of the active window. Read-only.

Remarks

The title of the active window is the text displayed in the window's title bar.


CodeModule Property (VBA Add-In Object Model)

 Copy code hover
[image]

CodeModule Property (VBA Add-In Object Model)
Send feedback

Returns an object representing the code behind the component. Read-only.

Remarks

The CodeModule property returns Nothing if the component doesn't have a code module associated with it.

Note Note

The CodePane object represents a visible code window. A given component can have several CodePane objects. The CodeModule object represents the code within a component. A component can only have one CodeModule object.


CommandBars Property (VBA Add-In Object Model)

 Copy code hover
[image]

CommandBars Property (VBA Add-In Object Model)
Send feedback

Contains all of the command bars in a project, including command bars that support shortcut menus.


CodePanes Property (VBA Add-In Object Model)

 Copy code hover
[image]

CodePanes Property (VBA Add-In Object Model)
Send feedback

Returns the collection of active CodePane objects. Read-only.


CodePaneView Property (VBA Add-In Object Model)

 Copy code hover
[image]

CodePaneView Property (VBA Add-In Object Model)
Send feedback

Returns a value indicating whether the code pane is in Procedure view or Full Module view. Read-only.

Return Values

The CodePaneView property return values are:

Constant | Description
vbext_cv_ProcedureView | The specified code pane is in Procedure view.
Vbext_cv_FullModuleView | The specified project is in Full Module view.


Connect Property

 Copy code hover
[image]

Connect Property
Send feedback

Returns or sets the connected state of an add-in.

Remarks

Returns True if the add-in is registered and currently connected (active).

Returns False if the add-in is registered, but not connected (inactive).


Collection Property (VBA Add-In Object Model)

 Copy code hover
[image]

Collection Property (VBA Add-In Object Model)
Send feedback

Returns the collection that contains the object you are working with. Read-only.

Remarks

Most objects in this object model have either a Parent property or a Collection property that points to the object's parent object.

Use the Collection property to access the properties, methods, and controls of the collection to which the object belongs.


CommandBarEvents Property (VBA Add-In Object Model)

 Copy code hover
[image]

CommandBarEvents Property (VBA Add-In Object Model)
Send feedback

Returns the CommandBarEvents object. Read-only.

Settings

The setting for the argument you pass to the CommandBarEvents property is:

Argument | Description
vbcontrol | Must be an object of type CommandBarControl.

Remarks

Use the CommandBarEvents property to return an event source object that triggers an event when a command bar button is clicked. The argument passed to the CommandBarEvents property is the command bar control for which the Click event will be triggered.


Count Property (VBA Add-In Object Model)

 Copy code hover
[image]

Count Property (VBA Add-In Object Model)
Send feedback

Returns a Long containing the number of items in a collection. Read-only.


CountOfDeclarationLines Property (VBA Add-In Object Model)

 Copy code hover
[image]

CountOfDeclarationLines Property (VBA Add-In Object Model)
Send feedback

Returns a Long containing the number of lines of code in the Declarations section of a code module. Read-only.


CountOfLines Property (VBA Add-In Object Model)

 Copy code hover
[image]

CountOfLines Property (VBA Add-In Object Model)
Send feedback

Returns a Long containing the number of lines of code in a code module. Read-only.


CountOfVisibleLines Property (VBA Add-In Object Model)

 Copy code hover
[image]

CountOfVisibleLines Property (VBA Add-In Object Model)
Send feedback

Returns a Long containing the number of lines visible in a code pane. Read-only.


Description Property (VBA Add-In Object Model)

 Copy code hover
[image]

Description Property (VBA Add-In Object Model)
Send feedback

Returns or sets a string expression containing a descriptive string associated with an object. For the VBProject object, read/write; for the Reference object, read-only.

Remarks

For the VBProject object, the Description property returns or sets a descriptive string associated with the active project.

For the Reference object, the Description property returns the descriptive name of the reference.


DesignerID Property

 Copy code hover
[image]

DesignerID Property
Send feedback

Read-only property that returns the ProgID of an ActiveX designer.


Designer Property (VBA Add-In Object Model)

 Copy code hover
[image]

Designer Property (VBA Add-In Object Model)
Send feedback

Returns the object that enables you to access the design characteristics of a component.

Remarks

If the object has an open designer, the Designer property returns the open designer; otherwise a new designer is created. The designer is a characteristic of certain VBComponent objects. For example, when you create certain types of VBComponent object, a designer is created along with the object. A component can have only one designer, and it's always the same designer. The Designer property enables you to access a component-specific object. In some cases, such as in standard modules and class modules, a designer isn't created because that type of VBComponent object doesn't support a designer.

The Designer property returns Nothing if the VBComponent object doesn't have a designer.


Events Property

 Copy code hover
[image]

Events Property
Send feedback

Supplies properties that enable add-ins to connect to all events in Visual Basic for Applications.

Syntax

object.Events

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


FileName Property

 Copy code hover
[image]

FileName Property
Send feedback

Returns the full path name of the project file or host document.

Syntax

object .Filename

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

Remarks

Projects have no name other than the file name.

The path name returned is always provided as an absolute path (for example, "c:\projects\myproject.vba"), even if it is shown as a relative path (such as "..\projects\myproject.vba").


FullPath Property (VBA Add-In Object Model)

 Copy code hover
[image]

FullPath Property (VBA Add-In Object Model)
Send feedback

Returns a String containing the path and file name of the referenced type library. Read-only.


GUID Property (VBA Add-In Object Model)

 Copy code hover
[image]

GUID Property (VBA Add-In Object Model)
Send feedback

Returns a String containing the class identifier of an object. Read-only.


HasOpenDesigner Property (VBA Add-In Object Model)

 Copy code hover
[image]

HasOpenDesigner Property (VBA Add-In Object Model)
Send feedback

Returns a Boolean value indicating whether or not the VBComponent object has an open designer. Read-only.

Return Values

The HasOpenDesigner property returns these values:

Value | Description
True | The VBComponent object has an open Design window.
False | The VBComponent object doesn't have an open Design window.


Height Property (VBA Add-In Object Model)

 Copy code hover
[image]

Height Property (VBA Add-In Object Model)
Send feedback

Returns or sets a Single containing the height of the window in twips. Read/write.

Remarks

Changing the Height property setting of a linked window or docked window has no effect as long as the window remains linked or docked.

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements will generate run-time errors when run on the Macintosh.


HelpContextID Property (VBA Add-In Object Model)

 Copy code hover
[image]

HelpContextID Property (VBA Add-In Object Model)
Send feedback

Returns or sets a String containing the context ID for a topic in a Microsoft Windows Help file. Read/write.


HelpFile Property (VBA Add-In Object Model)

 Copy code hover
[image]

HelpFile Property (VBA Add-In Object Model)
Send feedback

Returns or sets a String specifying the Microsoft Windows Help file for a project. Read/write.


IndexedValue Property (VBA Add-In Object Model)

 Copy code hover
[image]

IndexedValue Property (VBA Add-In Object Model)
Send feedback

Returns or sets a value for a member of a property that is an indexed list or an array.

Remarks

The value returned or set by the IndexedValue property is an expression that evaluates to a type that is accepted by the object. For a property that is an indexed list or array, you must use the IndexedValue property instead of the Value property. An indexed list is a numeric expression specifying index position.

IndexedValue accepts up to 4 indices. The number of indices accepted by IndexedValue is the value returned by the NumIndices property.

The IndexedValue property is used only if the value of the NumIndices property is greater than zero. Values in indexed lists are set or returned with a single index.


IsBroken Property (VBA Add-In Object Model)

 Copy code hover
[image]

IsBroken Property (VBA Add-In Object Model)
Send feedback

Returns a Boolean value indicating whether or not the Reference object points to a valid reference in the registry. Read-only.

Return Values

The IsBroken property returns these values:

Value | Description
True | The Reference object no longer points to a valid reference in the registry.
False | The Reference object points to a valid reference in the registry.


Left Property (VBA Add-In Object Model)

 Copy code hover
[image]

Left Property (VBA Add-In Object Model)
Send feedback

Returns or sets a Single containing the location of the left edge of the window on the screen in twips. Read/write.

Remarks

The value returned by the Left property depends on whether or not the window is linked or docked.

Note Note

Changing the Left property setting of a linked or docked window has no effect as long as the window remains linked or docked.

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements will generate run-time errors when run on the Macintosh.


Lines Property

 Copy code hover
[image]

Lines Property
Send feedback

Returns a string containing the specified number of lines of code.

Syntax

object .Lines( startline, count) As String

The Lines syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
startline | Required. A Long specifying the line number in which to start.
count | Required. A Long specifying the number of lines you want to return.

Remarks

The line numbers in a code module begin at 1.


LinkedWindowFrame Property (VBA Add-In Object Model)

 Copy code hover
[image]

LinkedWindowFrame Property (VBA Add-In Object Model)
Send feedback

Returns the Window object representing the frame that contains the window. Read-only.

Remarks

The LinkedWindowFrame property enables you to access the object representing the linked window frame, which has properties distinct from the window or windows it contains. If the window isn't linked, the LinkedWindowFrame property returns Nothing.

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements will generate run-time errors when run on the Macintosh.


LinkedWindows Property

 Copy code hover
[image]

LinkedWindows Property
Send feedback

Returns the collection of all linked windows contained in a linked window frame. Read-only.

Remarks

The LinkedWindows property is an accessor property (that is, a property that returns an object of the same type as the property name).


MainWindow Property (VBA Add-In Object Model)

 Copy code hover
[image]

MainWindow Property (VBA Add-In Object Model)
Send feedback

Returns a Window object representing the main window of the Visual Basic development environment. Read-only.

Remarks

You can use the Window object returned by the MainWindow property to add or remove docked windows. You can also use the Window object returned by the MainWindow property to maximize, minimize, hide, or restore the main window of the Visual Basic development environment.

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements will generate run-time errors when run on the Macintosh.


Major Property (VBA Add-In Object Model)

 Copy code hover
[image]

Major Property (VBA Add-In Object Model)
Send feedback

Returns a Long containing the major version number of the referenced type library. Read-only.

Remarks

The number returned by the Major property corresponds to the major version number stored in the type library to which you have set the reference.


Minor Property (VBA Add-In Object Model)

 Copy code hover
[image]

Minor Property (VBA Add-In Object Model)
Send feedback

Returns a Long indicating the minor version number of the referenced type library. Read-only.

Remarks

The number returned by the Minor property corresponds to the minor version number stored in the type library to which you have set the reference.


Mode Property (VBA Add-In Object Model)

 Copy code hover
[image]

Mode Property (VBA Add-In Object Model)
Send feedback

Returns a value containing the mode of the specified project. Read-only.

Return Values

The Mode property return values are:

Constant | Description
vbext_vm_Run | The specified project is in run mode.
vbext_vm_Break | The specified project is in break mode.
vbext_vm_Design | The specified project is in design mode.


Name Property (VBA Add-In Object Model)

 Copy code hover
[image]

Name Property (VBA Add-In Object Model)
Send feedback

Returns or sets a String containing the name used in code to identify an object. For the VBProject object and the VBComponent object, read/write; for the Property object and the Reference object, read-only.

Remarks

The following table describes how the Name property setting applies to different objects.

Object | Result of Using Name Property Setting
VBProject | Returns or sets the name of the active project.
VBComponent | Returns or sets the name of the component. An error occurs if you try to set the Name property to a name already being used or an invalid name.
Property | Returns the name of the property as it appears in the Property Browser. This is the value used to index the Properties collection. The name can't be set.
Reference | Returns the name of the reference in code. The name can't be set.

The default name for new objects is the type of object plus a unique integer. For example, the first new Form object is Form1, a new Form object is Form1, and the third TextBox control you create on a form is TextBox3.

An object's Name property must start with a letter and can be a maximum of 40 characters. It can include numbers and underline (_) characters but can't include punctuation or spaces. Forms and modules can't have the same name as another public object such as Clipboard, Screen, or App. Although the Name property setting can be a keyword, property name, or the name of another object, this can create conflicts in your code.


NumIndices Property (VBA Add-In Object Model)

 Copy code hover
[image]

NumIndices Property (VBA Add-In Object Model)
Send feedback

Returns the number of indices on the property returned by the Property object.

Remarks

The value of the NumIndices property can be an integer from 0 - 4. For most properties, NumIndices returns 0. Conventionally indexed properties return 1. Property arrays might return 2.


Object Property (VBA Add-In Object Model)

 Copy code hover
[image]

Object Property (VBA Add-In Object Model)
Send feedback

Returns or sets the value of an object returned by a property. Read/write.

Remarks

If a property returns an object, you must use the Object property to return or set the value of that object.


Parent Property (VBA Add-In Object Model)

 Copy code hover
[image]

Parent Property (VBA Add-In Object Model)
Send feedback

Returns the object or collection that contains another object or collection. Read-only.

Remarks

Most objects have either a Parent property or a Collection property that points to the object's parent object in this object model. The Collection property is used if the parent object is a collection.

Use the Parent property to access the properties, methods, and controls of an object's parent object.


ProcBodyLine Property

 Copy code hover
[image]

ProcBodyLine Property
Send feedback

Returns the first line of a procedure.

Syntax

object .ProcBodyLine( procname, prockind) As Long

The ProcBodyLine syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
procname | Required. A String containing the name of the procedure.
prockind | Required. Specifies the kind of procedure to locate. Because property procedures can have multiple representations in the module, you must specify the kind of procedure you want to locate. All procedures other than property procedures (that is, Sub and Function procedures) use vbext_pk_Proc.

You can use one of the following constants for the prockind argument:

Constant | Description
vbext_pk_Get | Specifies a procedure that returns the value of a property.
vbext_pk_Let | Specifies a procedure that assigns a value to a property.
vbext_pk_Set | Specifies a procedure that sets a reference to an object.
vbext_pk_Proc | Specifies all procedures other than property procedures.

Remarks

The first line of a procedure is the line on which the Sub, Function, or Property statement appears.


ProcCountLines Property

 Copy code hover
[image]

ProcCountLines Property
Send feedback

Returns the number of lines in the specified procedure.

Syntax

object .ProcCountLines( procname, prockind) As Long

The ProcCountLines syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
procname | Required. A String containing the name of the procedure.
prockind | Required. Specifies the kind of procedure to locate. Because property procedures can have multiple representations in the module, you must specify the kind of procedure you want to locate. All procedures other than property procedures (that is, Sub and Function procedures) use vbext_pk_Proc.

You can use one of the following constants for the prockind argument:

Constant | Description
vbext_pk_Get | Specifies a procedure that returns the value of a property.
vbext_pk_Let | Specifies a procedure that assigns a value to a property.
vbext_pk_Set | Specifies a procedure that sets a reference to an object.
vbext_pk_Proc | Specifies all procedures other than property procedures.

Remarks

The ProcCountLines property returns the count of all blank or comment lines preceding the procedure declaration and, if the procedure is the last procedure in a code module, any blank lines following the procedure.


ProcOfLine Property

 Copy code hover
[image]

ProcOfLine Property
Send feedback

Returns the name of the procedure that the specified line is in.

Syntax

object .ProcOfLine( line, prockind) As String

The ProcOfLine syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
line | Required. A Long specifying the line to check.
prockind | Required. Specifies the kind of procedure to locate. Because property procedures can have multiple representations in the module, you must specify the kind of procedure you want to locate. All procedures other than property procedures (that is, Sub and Function procedures) use vbext_pk_Proc.

You can use one of the following constants for the prockind argument:

Constant | Description
vbext_pk_Get | Specifies a procedure that returns the value of a property.
vbext_pk_Let | Specifies a procedure that assigns a value to a property.
vbext_pk_Set | Specifies a procedure that sets a reference to an object.
vbext_pk_Proc | Specifies all procedures other than property procedures.

Remarks

A line is within a procedure if it's a blank line or comment line preceding the procedure declaration and, if the procedure is the last procedure in a code module, a blank line or lines following the procedure.


ProcStartLine Property

 Copy code hover
[image]

ProcStartLine Property
Send feedback

Returns the line at which the specified procedure begins.

Syntax

object .ProcStartLine( procname, prockind) As Long

The ProcStartLine syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
procname | Required. A String containing the name of the procedure.
prockind | Required. Specifies the kind of procedure to locate. Because property procedures can have multiple representations in the module, you must specify the kind of procedure you want to locate. All procedures other than property procedures (that is, Sub and Function procedures) use vbext_pk_Proc.

You can use one of the following constants for the prockind argument:

Constant | Description
vbext_pk_Get | Specifies a procedure that returns the value of a property.
vbext_pk_Let | Specifies a procedure that assigns a value to a property.
vbext_pk_Set | Specifies a procedure that sets a reference to an object.
vbext_pk_Proc | Specifies all procedures other than property procedures.

Remarks

A procedure starts at the first line below the End Sub statement of the preceding procedure. If the procedure is the first procedure, it starts at the end of the general Declarations section.


ProgID Property

 Copy code hover
[image]

ProgID Property
Send feedback

Returns the ProgID (programmatic ID) for the control represented by the VBControl object.

Syntax

object .ProgID

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


Protection Property (VBA Add-In Object Model)

 Copy code hover
[image]

Protection Property (VBA Add-In Object Model)
Send feedback

Returns a value indicating the state of protection of a project. Read-only.

Return Values

The Protection property return values are:

Constant | Description
vbext_pp_locked | The specified project is locked.
vbext_pp_none | The specified project isn't protected.


ReferencesEvents Property (VBA Add-In Object Model)

 Copy code hover
[image]

ReferencesEvents Property (VBA Add-In Object Model)
Send feedback

Returns the ReferencesEvents object. Read-only.

Settings

The setting for the argument you pass to the ReferencesEvents property is:

Argument | Description
vbproject | If vbproject points to Nothing, the object that is returned will supply events for the References collections of all VBProject objects in the VBProjects collection. If vbproject points to a valid VBProject object, the object that is returned will supply events for only the References collection for that project.

Remarks

The ReferencesEvents property takes an argument and returns an event source object. The ReferencesEvents object is the source for events that are triggered when references are added or removed.


Saved Property (VBA Add-In Object Model)

 Copy code hover
[image]

Saved Property (VBA Add-In Object Model)
Send feedback

Returns a Boolean value indicating whether or not the object was edited since the last time it was saved. Read/write.

Return Values

The Saved property returns these values:

Value | Description
True | The object has not been edited since the last time it was saved.
False | The object has been edited since the last time it was saved.

Remarks

The SaveAs method sets the Saved property to True.

Note Note

If you set the Saved property to False in code, it returns False, and the object is marked as if it were edited since the last time it was saved.


SelectedVBComponent Property (VBA Add-In Object Model)

 Copy code hover
[image]

SelectedVBComponent Property (VBA Add-In Object Model)
Send feedback

Returns the selected component. Read-only.

Remarks

The SelectedVBComponent property returns the selected component in the Project window. If the selected item in the Project window isn't a component, SelectedVBComponent returns Nothing.


Top Property (VBA Add-In Object Model)

 Copy code hover
[image]

Top Property (VBA Add-In Object Model)
Send feedback

Returns or sets a Single specifying the location of the top of the window on the screen in twips. Read/write.

Remarks

The value returned by the Top property depends on whether or not the window is docked, linked, or in docking view.

Note Note

Changing the Top property setting of a linked or docked window has no effect as long as the window remains linked or docked.

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements will generate run-time errors when run on the Macintosh.


TopLine Property (VBA Add-In Object Model)

 Copy code hover
[image]

TopLine Property (VBA Add-In Object Model)
Send feedback

Returns a Long specifying the line number of the line at the top of the code pane or sets the line showing at the top of the code pane. Read/write.

Remarks

Use the TopLine property to return or set the line showing at the top of the code pane. For example, if you want line 25 to be the first line showing in a code pane, set the TopLine property to 25.

The TopLine property setting must be a positive number. If the TopLine property setting is greater than the actual number of lines in the code pane, the setting will be the last line in the code pane.


Type Property (VBA Add-In Object Model)

 Copy code hover
[image]

Type Property (VBA Add-In Object Model)
Send feedback

Returns a numeric or string value containing the type of object. Read-only.

Return Values

The Type property settings for the Window object are described in the following table:

Constant | Value | Description
vbext_wt_CodeWindow | 0 | Code window
vbext_wt_Designer | 1 | Designer
vbext_wt_Browser | 2 | Object Browser
vbext_wt_Immediate | 5 | Immediate window
vbext_wt_ProjectWindow | 6 | Project window
vbext_wt_PropertyWindow | 7 | Properties window
vbext_wt_Find | 8 | Find dialog box
vbext_wt_FindReplace | 9 | Search and Replace dialog box
vbext_wt_LinkedWindowFrame | 11 | Linked window frame
vbext_wt_MainWindow | 12 | Main window
vbext_wt_Watch | 3 | Watch window
vbext_wt_Locals | 4 | Locals window
vbext_wt_Toolbox | 10 | Toolbox
vbext_wt_ToolWindow | 15 | Tool window

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements will generate run-time errors when run on the Macintosh.

The Type property settings for the VBComponent object are described in the following table:

Constant | Value | Description
vbext_ct_StdModule | 1 | Standard module
vbext_ct_ClassModule | 2 | Class module
vbext_ct_MSForm | 3 | Microsoft Form
vbext_ct_ActiveXDesigner | 11 | ActiveX Designer
vbext_ct_Document | 100 | Document Module

The Type property settings for the Reference object are described in the following table:

Constant | Value | Description
vbext_rk_TypeLib | 0 | Type library
vbext_rk_Project | 1 | Project

The Type property settings for the VBProject object are described in the following table:

Constant | Value | Description
vbext_pt_HostProject | 100 | Host Project
vbext_pt_StandAlone | 101 | Standalone Project


Value Property (VBA Add-In Object Model)

 Copy code hover
[image]

Value Property (VBA Add-In Object Model)
Send feedback

Returns or sets a Variant specifying the value of the property. Read/write.

Remarks

Because the Value property returns a Variant, you can access any property. To access a list, use the IndexedValue property.

If the property that the Property object represents is read/write, the Value property is read/write. If the property is read-only, attempting to set the Value property causes an error. If the property is write-only, attempting to return the Value property causes an error.

The Value property is the default property for the Property object.


VBE Property (VBA Add-In Object Model)

 Copy code hover
[image]

VBE Property (VBA Add-In Object Model)
Send feedback

Returns the root of the VBE object. Read-only.

Remarks

All objects have a VBE property that points to the root of the VBE object.


VBProjects Property

 Copy code hover
[image]

VBProjects Property
Send feedback

Returns the VBProjects collection, which represents all of the projects currently open in the Visual Basic IDE.

Syntax

object.VBProjects

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


Version Property (VBA Add-In Object Model)

 Copy code hover
[image]

Version Property (VBA Add-In Object Model)
Send feedback

Returns a String containing the version of Visual Basic for Applications that the application is using. Read-only.

Remarks

The Version property value is a string beginning with one or two digits, a period, and two digits; the rest of the string is undefined and may contain text or numbers.


Visible Property (VBA Add-In Object Model)

 Copy code hover
[image]

Visible Property (VBA Add-In Object Model)
Send feedback

For the Window object, returns or sets a Boolean value that specifies the visibility of a window. Read/write. For the CodePane object, returns a Boolean value that indicates whether or not the code pane is visible in the window. Read-only.

Return Values

The Visible property returns the following values:

Value | Description
True | (Default) Object is visible.
False | Object is hidden.


Width Property (VBA Add-In Object Model)

 Copy code hover
[image]

Width Property (VBA Add-In Object Model)
Send feedback

Returns or sets a Single containing the width of the window in twips. Read/write.

Remarks

Changing the Width property setting of a linked window or docked window has no effect as long as the window remains linked or docked.

Important note Important

Objects, properties, and methods for controlling linked windows, linked window frames, and docked windows are included on the Macintosh for compatibility with code written in Windows. However, these language elements will generate run-time errors when run on the Macintosh.


Window Property (VBA Add-In Object Model)

 Copy code hover
[image]

Window Property (VBA Add-In Object Model)
Send feedback

Returns the window in which the code pane is displayed. Read-only.


Windows Property

 Copy code hover
[image]

Windows Property
Send feedback

Returns the Window object, which represents a window in the Visual Basic IDE.

Syntax

object.Window

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


WindowState Property (VBA Add-In Object Model)

 Copy code hover
[image]

WindowState Property (VBA Add-In Object Model)
Send feedback

Returns or sets a numeric value specifying the visual state of the window. Read/write.

Settings

The WindowState property returns or sets the following values:

Constant | Value | Description
vbext_ws_Normal | 0 | (Default) Normal
vbext_ws_Minimize | 1 | Minimized (minimized to an icon)
vbext_ws_Maximize | 2 | Maximized (enlarged to maximum size)


Properties Property (VBA Add-In Object Model)

 Copy code hover
[image]

Properties Property (VBA Add-In Object Model)
Send feedback

Returns the properties of an object. Read-only.

Remarks

The Properties property is an accessor property (that is, a property that returns an object of the same type as the property name).


References Property

 Copy code hover
[image]

References Property
Send feedback

Returns the set of references in a project. Read-only.

Remarks

The References property is an accessor property (that is, a property that returns an object of the same type as the property name).


Visual Basic user interface Help

 Copy code hover
[image]

Visual Basic user interface Help
Send feedback

In this section

  • <Host application> Command (View Menu)

  • <Project Name> Properties Command (Tools Menu)

  • Add Procedure Dialog Box

  • Add-In Manager Command (Add-Ins Menu)

  • Add-In Manager Dialog Box

  • Add-Ins Menu

  • Additional Controls Command (Shortcut Menu)

  • Additional Controls Command (Tools Menu)

  • Additional Controls Dialog Box

  • Align Commands (Format Menu)

  • Ambiguous selection (Visual Basic for Applications)

  • Arrange Buttons Commands (Format Menu)

  • Bookmarks Commands (Edit Menu)

  • Break Command (Run Menu)

  • Button Editor Dialog Box

  • Call Stack Command (View Menu)

  • Call Stack Dialog Box

  • Center in Form Commands (Format Menu)

  • Clear All Breakpoints Command (Debug Menu)

  • Clearand Delete Commands (Edit Menu)

  • Close & Return to <host application> Command (File Menu)

  • Close Command (Shortcut Menu)

  • Close Project Command (File Menu)

  • Code Command (View Menu)

  • Code Editing Keys

  • Code Window

  • Code Window General Use Keys

  • Code Window Keyboard Shortcuts

  • Code Window Navigation Keys

  • Collapse Parent Command (Shortcut Menu)

  • Commands Tab (Customize Dialog Box)

  • Comment Block and Uncomment Block Commands

  • Compile <project> Command (Debug Menu)

  • Complete Word Command (Edit Menu)

  • Components Command (Insert Menu)

  • Components Dialog Box

  • Controls Tab (Components Dialog Box)

  • Copy Command (Object Browser Shortcut Menu)

  • Copy Here and Move Here Commands (Shortcut Menu)

  • Customize <item> Command (Shortcut Menu)

  • Customize Command (Shortcut Menu)

  • Customize Control Dialog Box

  • Customize Dialog Box

  • Cut, Copy, Paste, and Delete Commands (Edit Menu)

  • Data Tips Window

  • Data Types Displayed in Locals Window

  • Debug Menu

  • Debugging Tab (Project Properties Dialog Box)

  • Definition Command (Shortcut Menu)

  • Definition Command (View Menu)

  • Delete <item> Command (Shortcut Menu)

  • Delete Page Command (Shortcut Menu)

  • Delete Watch Command (Shortcut Menu)

  • Design Mode and Exit Design Mode Commands (Run Menu)

  • Designers Tab (Components Dialog Box)

  • Digital Signature Command (Tools Menu)

  • Digital Signature Dialog Box

  • Dockable Command (Shortcut Menu)

  • Docking Tab (Options Dialog Box)

  • Edit Menu

  • Edit Watch Command (Debug Menu)

  • Edit Watch Dialog Box

  • Editor Format Tab (Options Dialog Box)

  • Editor Tab (Options Dialog Box)

  • Editor Toolbar

  • Export File Dialog Box

  • File Command (Insert Menu)

  • File Menu

  • Find Command (Edit Menu)

  • Find Whole Word Only Command (Object Browser Shortcut Menu)

  • Font Dialog Box

  • Format Menu

  • General Tab (Options Dialog Box)

  • General Tab (Project Properties Dialog Box)

  • Global Keys

  • Group and Ungroup Commands (Format Menu)

  • Group Members Command (Object Browser Shortcut Menu)

  • Help Command (Shortcut Menu)

  • Help Menu

  • Hide Command (Shortcut Menu)

  • Horizontal Spacing Commands (Format Menu)

  • Immediate Window

  • Immediate Window Command (View Menu)

  • Immediate Window Keyboard Shortcuts

  • Import File and Export File Commands (File Menu)

  • Import File Dialog Box

  • Import Page and Export Page Commands (Shortcut Menu)

  • Indent Command (Edit Menu)

  • Insert File Dialog Box

  • Insert Menu

  • Last Position Command (View Menu)

  • Load Picture, Load Icon Dialog Boxes

  • Locals Window

  • Locals Window Command (View Menu)

  • Macros Command (Tools Menu)

  • Macros Dialog Box

  • Make <Project> Command (File Menu)

  • Make Same Size Commands (Format Menu)

  • Make Tab (Project Properties Dialog Box)

  • Margin Indicators

  • Member Options Dialog Box

  • Menu Shortcut Keys Available in the Code Window

  • Module and Class Module Commands (Insert Menu)

  • Move Command (Shortcut Menu)

  • New Page Command (Shortcut Menu)

  • New Project Command (File Menu)

  • New Project Dialog Box

  • New Toolbar Dialog Box

  • Object Browser

  • Object Browser Command (View Menu)

  • Object Command (View Menu)

  • Open Project Command (File Menu)

  • Open Project Dialog Box

  • Options Command (Tools Menu)

  • Options Dialog Box

  • Options Tab (Customize Dialog Box)

  • Order Commands (Format Menu)

  • Outdent Command (Edit Menu)

  • Page Order Dialog Box

  • Parameter Info Command (Edit Menu)

  • Print Command (File Menu)

  • Print Setup Dialog Box

  • Procedure Command (Insert Menu)

  • Project Explorer

  • Project Properties Dialog Box

  • Properties Command (Object Browser Shortcut Menu)

  • Properties Command (Shortcut Menu)

  • Properties Window

  • Properties Window Command (View Menu)

  • Properties Window Keyboard Shortcuts

  • Protection Tab (Project Properties Dialog Box)

  • Quick Info Command (Edit Menu)

  • Quick Watch Command (Tools Menu)

  • Quick Watch Dialog Box

  • Redo, Undo Commands (Edit Menu)

  • References Command (Tools Menu)

  • References Dialog Box

  • Remove <Item> Command (File Menu)

  • Rename Command (Shortcut Menu)

  • Rename Toolbar Dialog Box

  • Replace Command (Edit Menu)

  • Reset <project> Command (Run Menu)

  • Run Menu

  • Run Project and Stop Project Commands (Run Menu)

  • Run Sub/UserForm, Continue, and Run Macro Commands (Run Menu)

  • Run to Cursor Command (Debug Menu)

  • Save <host document> Command (File Menu)

  • Security Dialog Box

  • Select All Command (Edit Menu)

  • Select Certificate Dialog Box

  • Select Constant Command (Edit Menu)

  • Select Member Command (Edit Menu)

  • Set Next Statement Command (Debug Menu)

  • Show Hidden Members Command (Object Browser Shortcut Menu)

  • Show Next Statement Command (Debug Menu)

  • Size Command (Shortcut Menu)

  • Size to Fit Command (Format Menu)

  • Size to Grid Command (Format Menu)

  • Standard Toolbar

  • Step Into, Step Over, Step Out Commands (Debug Menu)

  • Tab Order Command (View Menu)

  • Tab Order Dialog Box

  • Toggle Breakpoint Command (Debug Menu)

  • Toggle Commands (Shortcut Menu)

  • Toolbars Command (View Menu)

  • Toolbars Tab (Customize Dialog Box)

  • Toolbox

  • Toolbox Command (View Menu)

  • Tools Menu

  • UserForm Command (Insert Menu)

  • UserForm Command Bar

  • UserForm Windowc (Visual Basic User Interface)

  • UserForm Window Keys

  • Vertical Spacing Commands (Format Menu)

  • View Definition Command (Object Browser Shortcut Menu)

  • View Menu

  • View Object and View Code Commands (Shortcut Menu)

  • Visual Basic Menus

  • Watch Window

  • Watch Window Command (View Menu)

  • Watch Window Keyboard Shortcuts

  • Wildcard Characters used in String Comparisons

  • Window Menu Commands

  • Zoom Command

  • Add Watch Command (Debug Menu)

  • Add Watch Dialog Box

  • Debug Toolbar

  • Icons Used in the Object Browser and Code Windows

  • Project Explorer Command (View Menu)

  • Project Explorer Keyboard Shortcuts


 Copy code hover
[image]

<Host application> Command (View Menu)
Send feedback

Moves the host application on top of the Visual Basic editor so that you can view it. The name of the command changes to the name of the host application.

Keyboard shortcut: ALT+F11.


 Copy code hover
[image]

<Project Name> Properties Command (Tools Menu)
Send feedback

Displays the Project Properties dialog box where you can set protection for and options specific to your project.

Toolbar shortcut: .


Add Procedure Dialog Box

 Copy code hover
[image]

Add Procedure Dialog Box
Send feedback

Inserts a new Sub, Function, or Property procedure. The Add Procedure dialog box also allows you to set the scope to public or private, and make all local variables in the procedure static.

Dialog Box Options

Name

Lists a name for the new procedure.

Type

Identifies the type of procedure to create.

  • Sub — Creates a new Sub procedure.

  • Function — Creates a new Function procedure.

  • Property — Creates a new Let property and Get property procedure pair.

Scope

Sets the procedure's scope to either Public or Private.

All Local Variables as Statics

Adds the Static keyword to the procedure definition.

OK

Inserts the procedure template in the Code window.

Cancel

Closes the dialog box without inserting a new procedure.


Add-In Manager Command (Add-Ins Menu)

 Copy code hover
[image]

Add-In Manager Command (Add-Ins Menu)
Send feedback

Displays the Add-In Manager dialog box, which you use to load and unload add-ins to extend the Visual Basic for Applications development environment.


Add-In Manager Dialog Box

 Copy code hover
[image]

Add-In Manager Dialog Box
Send feedback

Allows you to register an add-in, load or unload it, and set its load behavior. If you close only the visible portions of an add-in — by double-clicking its system menu or by clicking its Close button, for example — its forms disappear from the screen, but the add-in is still present in memory. The add-in object itself will always stay resident in memory until the add-in is disconnected through the Add-In Manager dialog box.

To open the Add-In Manager, Add-In Manager from the Add-Ins menu.

Dialog Box Options

Add-Ins List

  • Available Add-Ins — Lists available add-ins.

  • Load Behavior — Displays the load behavior for the selected add-in.

Description

Displays a description of what the add-in does.

Load Behavior

  • Loaded/Unloaded — Loads or unloads the selected add-in.

  • Load On Startup — Loads selected add-in on startup of development environment.

  • Command Line — Loads the selected add-in when the development environment is started from the command prompt or from a script.

OK

Updates the load behavior of selected add-ins.

Cancel

Cancels all updates made in session.


Add-Ins Menu

 Copy code hover
[image]

Add-Ins Menu
Send feedback

Add-In Manager


Additional Controls Command (Shortcut Menu)

 Copy code hover
[image]

Additional Controls Command (Shortcut Menu)
Send feedback

Displays the Additional Controls dialog box so that you can add controls.


Additional Controls Command (Tools Menu)

 Copy code hover
[image]

Additional Controls Command (Tools Menu)
Send feedback

Displays the Additional Controls dialog box where you can add controls or insertable objects (such as a Microsoft Word Document) to the Toolbox.


Additional Controls Dialog Box

 Copy code hover
[image]

Additional Controls Dialog Box
Send feedback

Allows you add controls to your project's Toolbox.

Dialog Box Options

Available Controls

Displays the available custom controls.

Note Note

You cannot remove a control that is used in your project.

Show

Determines which items are listed in the Available Controls list. You can select any or all of the following options.

  • Selected Items Only — Displays only those items in the Available Controls list which you have selected to include in the project.

Path

Displays the path of the item selected in the Available Controls list.


Align Commands (Format Menu)

 Copy code hover
[image]

Align Commands (Format Menu)
Send feedback

Aligns selected objects with each other using the control with the white grab handles as the reference.

Lefts

Aligns the horizontal position of the selected objects, putting the left-most edges in line with the control with the white grab handles.

Toolbar shortcut: .

Centers

Aligns the horizontal position of the selected objects, putting the centers in line with the control with the white grab handles.

Toolbar shortcut: .

Rights

Aligns the horizontal position of the selected objects, putting the right-most edges in line with the control with the white grab handles.

Toolbar shortcut: .

Tops

Aligns the vertical position of the selected objects, putting the tops in line with the control with the white grab handles.

Toolbar shortcut: .

Middles

Aligns the vertical position of selected objects, putting the middles in line with the control with the white grab handles.

Toolbar shortcut: .

Bottoms

Aligns the vertical position of the selected objects, putting the bottoms in line with the control with the white grab handles.

Toolbar shortcut: .

To Grid

Aligns the top left of the selected objects to the closest grid. The object is not resized.

Toolbar shortcut: .


Ambiguous selection (Visual Basic for Applications)

 Copy code hover
[image]

Ambiguous selection (Visual Basic for Applications)
Send feedback

Either you have not selected a keyword or you have requested Help on a component of the integrated development environment (IDE). If you were trying to select a keyword, try reselecting a single keyword. If you were trying to get information on the IDE, click one of the following:

Code or Module Window

Immediate Window or Pane

Locals Windows or Pane

Object Browser

Watch Window or Pane


Arrange Buttons Commands (Format Menu)

 Copy code hover
[image]

Arrange Buttons Commands (Format Menu)
Send feedback

Arranges selected command buttons along the bottom or edge of a form.

Bottom

Arranges to the bottom left side of the form with equal spacing between each of them.

Toolbar shortcut: .

Right

Arranges to the top right side of the form with equal spacing between each of them.

Toolbar shortcut: .


Bookmarks Commands (Edit Menu)

 Copy code hover
[image]

Bookmarks Commands (Edit Menu)
Send feedback

Displays a menu that you can use to create or remove placeholders in the Code window, move to the next or preceding bookmark, or clear all of the bookmarks. Bookmarks mark lines of code so that you can easily return to them at a later time.

When you add a bookmark, a [image] appears next to the line of code where the bookmark is inserted.

Toggle Bookmark

Toggles a bookmark on or off.

Toolbar button:

Next Bookmark

Moves the insertion point to the next bookmark.

Toolbar button:

Previous Bookmark

Moves the insertion point to the previous bookmark.

Toolbar button:

Clear All Bookmarks

Removes all bookmarks.

Toolbar button:


Break Command (Run Menu)

 Copy code hover
[image]

Break Command (Run Menu)
Send feedback

Stops execution of a program while it's running and switches to break mode. Any statement being executed when you choose this command is displayed in the Code window with [image] in the left margin if you checked Margin Indicator Bar in the Editor Format tab of the Options dialog box. If the application is waiting for events in the idle loop (no statement is being executed), no statement is highlighted until an event occurs.

Some editing changes made in break mode may require you to restart your program for the changes to take effect.

Toolbar button: . Keyboard shortcut: CTRL+BREAK.


Button Editor Dialog Box

 Copy code hover
[image]

Button Editor Dialog Box
Send feedback

Provides the tools to modify Toolbar icons.

Dialog Box Options

Picture

Shows the icon pixel by pixel.

Move

Moves the picture around so that you have access to all parts of it.

  • — Moves the picture up one row each time you click it until the top row of pixels is visible.

  • — Moves the picture down one row each time you click it until the bottom row of pixels is visible.

  • — Moves the picture to the right one column each time you click it until the right-most column is visible.

  • — Moves the picture to the left one column each time you click it until the left-most column is visible.

Colors

Changes the color of the pixel. You click on the color you want and then click on the pixel that you want to appear with that color.

Erase — Removes the color from the pixel you click on after you click on the Erase box.

Preview

Shows you how your icon will appear as you make the changes.

Clear

Clears all of the color and picture from the picture box.

OK

Assigns the picture to the control.


Call Stack Command (View Menu)

 Copy code hover
[image]

Call Stack Command (View Menu)
Send feedback

Displays the Call Stack dialog box, which lists the procedures that have started but are not completed. Available only in break mode.

When Visual Basic is executing the code in a procedure, that procedure is added to a list of active procedure calls. If that procedure then calls another procedure, there are two procedures on the list of active procedure calls. Each time a procedure calls another Sub, Function, or Property procedure, it is added to the list. Each procedure is removed from the list as execution is returned to the calling procedure. Procedures called from the Immediate window are also added to the calls list.

You can also display the Call Stack dialog box by clicking the Calls button (...) next to the Procedure box in the Locals window.

Toolbar shortcut: . Keyboard shortcut: CTRL+L.


Call Stack Dialog Box

 Copy code hover
[image]

Call Stack Dialog Box
Send feedback

Displays a list of currently active procedure calls during break mode. When executing code in a procedure, that procedure is added to a list of active procedure calls. Each time a procedure calls another procedure, it is added to the list. Called procedures are removed from the list when execution returns to the calling procedure. Procedures called from the Immediate window are also added to the calls list.

Dialog Box Options

Project Module Function

Lists the procedures.

Show

Moves the insertion point to the location where the call was made and turns on the Call Stack indicator, [image].


Center in Form Commands (Format Menu)

 Copy code hover
[image]

Center in Form Commands (Format Menu)
Send feedback

Centers selected objects on the central axes of the form.

Horizontally

Aligns the middles of the selected objects to a horizontal line in the middle of the form.

Toolbar shortcut: .

Vertically

Aligns the centers of the selected objects to a vertical line in the center of the form.

Toolbar shortcut: .


Clear All Breakpoints Command (Debug Menu)

 Copy code hover
[image]

Clear All Breakpoints Command (Debug Menu)
Send feedback

Removes all breakpoints in your project. Your application may still interrupt execution, however, if you have set a watch expression or selected the Break on All Errors option in the General tab of the Options dialog box. You cannot undo the Clear All Breakpoints command.

Toolbar shortcut: . Keyboard shortcut: CTRL+SHIFT+F9.


Clearand Delete Commands (Edit Menu)

 Copy code hover
[image]

Clearand Delete Commands (Edit Menu)
Send feedback

Clear

Deletes text only when a module is active.

Delete

At other times, changes to the Delete command that deletes the currently selected control, text, or watch expression. You can undo the Delete command in the Code window or in the form if you deleted the control from the form.

Toolbar shortcut: . Keyboard shortcut: DELETE.

Not available at run time.


Close & Return to

 Copy code hover
[image]

Close & Return to <host application> Command (File Menu)
Send feedback

Closes the development environment and returns you to the host application. Visual Basic is hidden but remains in memory.


Close Command (Shortcut Menu)

 Copy code hover
[image]

Close Command (Shortcut Menu)
Send feedback

Closes the selected window.


Close Project Command (File Menu)

 Copy code hover
[image]

Close Project Command (File Menu)
Send feedback

Closes the current project.

If the project contains any unsaved changes, you are prompted to save the project before closing.

Note Note

This feature is not available in all versions of the Visual Basic Editor.


Code Command (View Menu)

 Copy code hover
[image]

Code Command (View Menu)
Send feedback

Displays or activates the Code window for a currently selected object.

Toolbar shortcut: . Keyboard shortcut: F7.


Code Editing Keys

 Copy code hover
[image]

Code Editing Keys
Send feedback

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

Press | To
CTRL+C | Copy the selected text to the Clipboard.
CTRL+X | Cut the selected text to the Clipboard.
DELETE or 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+Y | Cut the current line to the Clipboard.
CTRL+DELETE | Delete to the end of the word.
CTRL+BACKSPACE | Delete to the beginning of the word.
SHIFT+F4 | Find Next: repeat text search down through your code. If no text search has been done, the Find dialog box is displayed.
SHIFT+F3 | Find Previous: repeat text search up through your code. If no text search has been done, the Find dialog box is displayed.
SHIFT+TAB | Remove indent.


Code Window

 Copy code hover
[image]

Code Window
Send feedback

Use the Code window to write, display, and edit Visual Basic code. You can open as many Code windows as you have modules, so you can easily view the code in different forms or modules, and copy and paste between them.

You can open a Code window from:

  • The Project window, by selecting a form or module, and choosing the View Code button.

  • A UserForm window, by double-clicking a control or form, choosing Code from the View menu, or pressing F7.

You can drag selected text to:

  • A different location in the current Code window.

  • Another Code window.

  • The Immediate and Watch windows.

  • The Recycle Bin.

Window Elements

Object Box

Displays the name of the selected object. Click the arrow to the right of the list box to display a list of all objects associated with the form.

Procedures/Events Box

Lists all the events recognized by Visual Basic for a form or control displayed in the Object box. When you select an event, the event procedure associated with that event name is displayed in the Code window.

If (General) is displayed in the Object box, the Procedure box lists any declarations and all of the general procedures that have been created for the form. If you are editing module code, the Procedure box lists all of the general procedures in the module. In either case, the procedure you select in the Procedure box is displayed in the Code window.

All the procedures in a module appear in a single, scrollable list that is sorted alphabetically by name. Selecting a procedure using the drop down list boxes at the top of the Code window moves the cursor to the first line of code in the procedure you select.

Split 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 Procedures/Events box applies to the code in the pane that has the focus. Dragging the bar to the top or the bottom of the window or double-clicking the bar closes a pane.

Margin Indicator Bar

A gray area on the left side of the Code window where margin indicators are displayed.

Procedure View Icon

Displays the selected procedure. Only one procedure at a time is displayed in the Code window.

Full Module View Icon

Displays the entire code in the module.


Code Window General Use Keys

 Copy code hover
[image]

Code Window General Use Keys
Send feedback

Use these key combinations in the Code window:

Press | To
F1 | Get context-sensitive Help on functions, statements, methods, properties, or events.
F2 | Display the Object Browser.
F9 | Set or remove a breakpoint.
CTRL+SHIFT+F9 | Clear all breakpoints.
F5 | Run a Sub/UserForm or macro.
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.
HOME | Move the cursor to the beginning of text in a line.
END | Move the cursor to the end of text in a line.
Double-click on the split bar | Delete the split bar.
SHIFT+F10 | View shortcut menu.
ALT+F5 | Runs the error handler code or returns the error to the calling procedure. Does not affect the setting for error trapping on the General tab of the Options dialog box.
ALT+F8 | Steps into the error handler or returns the error to the calling procedure. Does not affect the setting for error trapping on the General tab of the Options dialog box.
CTRL+J | Turn on ListProperties/Methods.
CTRL+SHIFT+J | Turn on List Constants.
CTRL+I | Turn on Quick Info.
CTRL+SHIFT+I | Turn on Parameter Info.
CTRL+SPACEBAR | Turn on Complete Word.


Code Window Keyboard Shortcuts

 Copy code hover
[image]

Code Window Keyboard Shortcuts
Send feedback

You can use the following shortcut keys to access commands in the Code window.

Description | Shortcut Keys
View Code window | F7
View Object Browser | F2
Find | CTRL+F
Replace | CTRL+H
Find Next | F3
Find Previous | SHIFT+F3
Next procedure | CTRL+DOWN ARROW
Previous procedure | CTRL+UP ARROW
View definition | SHIFT+F2
Shift one screen down | CTRL+PAGE DOWN
Shift one screen up | CTRL+PAGE UP
Go to last position | CTRL+SHIFT+F2
Beginning of module | CTRL+HOME
End of module | CTRL+END
Move one word to right | CTRL+RIGHT ARROW
Move one word to left | CTRL+LEFT ARROW
Move to end of line | END
Move to beginning of line | HOME
Undo | CTRL+Z
Delete current line | CTRL+Y
Delete to end of word | CTRL+DELETE
Indent | TAB
Outdent | SHIFT+TAB
Clear all breakpoints | CTRL+SHIFT+F9
View shortcut menu | SHIFT+F10


Code Window Navigation Keys

 Copy code hover
[image]

Code Window Navigation Keys
Send feedback

Use these key combinations to navigate in the Code window:

Press | To
CTRL+F2 | Move the insertion point into the Object box.
SHIFT+F2 | Go to the definition of the selected procedure.
CTRL+DOWN ARROW | Display the next procedure.
CTRL+UP ARROW | Display the previous procedure.
PAGE DOWN | Page down through the procedures in your code.
PAGE UP | Page up through the procedures in your code.
CTRL+SHIFT+F2 | Go back to the last position in your code.
CTRL+HOME | Go to the beginning of the module.
CTRL+END | Go to the end of the module.
CTRL+RIGHT ARROW | Go one word to the right.
CTRL+LEFT ARROW | Go one word to the left.
END | Go to the end of the line.
HOME | Go to the beginning of the line.
CTRL+PAGE DOWN | Go to the bottom of the current procedure.
CTRL+PAGE UP | Go to the top of the current procedure.
F6 | Switch between Code window panes (when the window is split).


Collapse Parent Command (Shortcut Menu)

 Copy code hover
[image]

Collapse Parent Command (Shortcut Menu)
Send feedback

Shrinks the list of items in the Locals or Watch window to the parent item. When you collapse a list, the icon to the left of the expression changes from a minus sign (-) to a plus sign (+).


Commands Tab (Customize Dialog Box)

 Copy code hover
[image]

Commands Tab (Customize Dialog Box)
Send feedback

Allows you to add controls and modify existing controls on the Menu bar or any toolbar. You can also modify the button image and text of your added commands.

Tab Options

Categories

Lists the different command categories.

Commands

Lists the controls available for the category you select in the Categories list. You can drag the command to the toolbar where you want the command to reside. To add the command to a menu, drag it over the menu's title and then into the location in the menu that appears.

Description

Displays a QuickTip for the currently selected control.

Modify Selection

Allows you to change the selected command.

  • Reset — Resets the command to the default.

  • Delete — Deletes the command.

  • Name — Changes the name of the control to the name you type into the box. By using the ampersand (&), you can also set shortcut keys.

  • Copy Button Image — Copies the button image to the Clipboard.

  • Paste Button Image — Pastes the button image from the Clipboard.

  • Reset Button Image — Resets the button image to its default setting.

  • Edit Button Image — Displays the Button Editor dialog box.

  • Change Button Image — Displays a list of button images from which you can select a different image for your button.

  • Default Style — For toolbar buttons, shows only the icon. For menu items, shows the icon and the name.

  • Text Only (Always) — Shows the command name only.

  • Text Only (in Menus) — Hides the icon, if any, for menu items. This options has no effect on toolbar buttons.

  • Image and Text — For toolbars, shows both the icon and name. This option has no effect on menu items.

  • Begin a Group — For toolbars, puts a separator line before the control. Dimmed when the control is at the beginning of the toolbar.


Comment Block and Uncomment Block Commands

 Copy code hover
[image]

Comment Block and Uncomment Block Commands
Send feedback

Adds and removes the comment character, an apostrophe, for each line of a selected block of text. If you do not have text selected and you choose the Comment Block or Uncomment Block command, the comment character is added or removed in the line where the pointer is located.

Comment Block

Adds the comment character to each line of a selected block of text.

Toolbar button: .

Uncomment Block

Removes the comment character from each line of a selected block of text.

Toolbar button: .


Compile

 Copy code hover
[image]

Compile <project> Command (Debug Menu)
Send feedback

Compiles your project.

Toolbar shortcut: .


Complete Word Command (Edit Menu)

 Copy code hover
[image]

Complete Word Command (Edit Menu)
Send feedback

Fills in the rest of the word you are typing once you have entered enough characters for Visual Basic to identify the word you want.

Toolbar shortcut: . Keyboard shortcut: CTRL+SPACEBAR.


Components Command (Insert Menu)

 Copy code hover
[image]

Components Command (Insert Menu)
Send feedback

Displays the Components dialog box from which you can add designers to the Insert menu.

Note Note

This feature is not available in all versions of the Visual Basic Editor.


Components Dialog Box

 Copy code hover
[image]

Components Dialog Box
Send feedback

Allows you to add components - controls, designers - to your project.

Dialog Box Options

Tabs

List components you can add by their category.

  • Controls

  • Designers

Apply

Adds the selected controls to the Toolbox or designer to the Insert menu without closing the dialog box.

OK

Adds the selected controls to the Toolbox or designer to the Insert menu and closes the Components dialog box.


Controls Tab (Components Dialog Box)

 Copy code hover
[image]

Controls Tab (Components Dialog Box)
Send feedback

Allows you to add controls to your project's Toolbox.

Note Note

This feature is not available in all versions of the Visual Basic Editor.

Tab Options

Available Controls List

Displays the available controls. You add a control by selecting the check box next to its name.

Note Note

You can't remove a control that is used in your project.

Path

Displays the path of the control selected in the Available Controls box.

Browse

Displays the Add ActiveX Control dialog box where you can locate and open the control you want.

Selected Items Only

When selected, displays only those controls in the Available Controls list which you have selected to include in the project.

Apply

Adds the selected controls to the Toolbox without closing the dialog box.

OK

Adds the selected controls to the Toolbox and closes the Components dialog box.


Copy Command (Object Browser Shortcut Menu)

 Copy code hover
[image]

Copy Command (Object Browser Shortcut Menu)
Send feedback

Copies the text for the selected class or member to the Clipboard.


Copy Here and Move Here Commands (Shortcut Menu)

 Copy code hover
[image]

Copy Here and Move Here Commands (Shortcut Menu)
Send feedback

Allows you to use a drag-and-drop operation on controls on the form. Select a control using the right mouse button, hold it down and then drag the control. When you release the mouse button, a shortcut menu appears with the following commands.

Copy Here

Copies the selected control to the location where you dragged your cursor.

Move Here

Moves the selected control to the location where you dragged your cursor.

Cancel

Cancels the operation.


Customize

 Copy code hover
[image]

Customize <item> Command (Shortcut Menu)
Send feedback

Displays the Customize Control dialog box where you can change the tool tip text, or the control icon for the selected item.


Customize Command (Shortcut Menu)

 Copy code hover
[image]

Customize Command (Shortcut Menu)
Send feedback

Displays the Customize dialog box where you can add, delete, modify, or create custom toolbars.


Customize Control Dialog Box

 Copy code hover
[image]

Customize Control Dialog Box
Send feedback

Allows you to add ToolTips and modify the icon for your control.

Dialog Box Options

Tool Tip Text

Contains the text for the tool tip.

Preview

Shows the icon that you choose to use for the control.

Edit Picture

Displays the Edit Picture dialog box where you can modify the icon.

Load Picture

Displays the Load Picture dialog box. The Load Picture dialog box is a standard Open common dialog box.


Customize Dialog Box

 Copy code hover
[image]

Customize Dialog Box
Send feedback

Allows you to customize your toolbars and menus.

Tabs

Toolbars

Allows you to create, rename, delete, and reset your toolbars.

Commands

Contains commands you can drag to your menus and toolbars.

Options

Allows you to change the size of your toolbar buttons, to show ToolTips and shortcut keys, and to add animation to your menus.


Cut, Copy, Paste, and Delete Commands (Edit Menu)

 Copy code hover
[image]

Cut, Copy, Paste, and Delete Commands (Edit Menu)
Send feedback

Cut

Removes the selected control or text and places it on the Clipboard. You must select at least one character or control for this command to be available. You can undo the Cut command when used on a control.

Toolbar shortcut: . Keyboard shortcut: CTRL+X or SHIFT+DELETE.

Copy

Copies the selected control or text onto the Clipboard. You must select at least one character or control for this command to be available. You cannot undo the Copy command in the Code window.

Toolbar shortcut: . Keyboard shortcut: CTRL+C or CTRL+INSERT

Paste

Inserts the contents of the Clipboard at the current location. Text is placed at the insertion point.

Pasted controls are placed in the middle of the form.

You can undo the Paste command in the Code window or in the form if you pasted the control onto the form.

Toolbar shortcut: . Keyboard shortcut: CTRL+V or SHIFT+INS.

Delete

Deletes the currently selected control, text, or watch expression. You can undo the Delete command only in the Code window.

Note Note

To delete a file from your disk, use the standard deletion procedures for your operating system.

Toolbar shortcut: . Keyboard shortcut: DEL.

Not available at run time.


Data Tips Window

 Copy code hover
[image]

Data Tips Window
Send feedback

A box that displays the value of the variable over which your cursor is placed.

For example, if you set and then set breakpoint before the end of your code, when you run your code and place your cursor over the "x", the value 5 appears in the Data Tips window.

Available in break mode.


Data Types Displayed in Locals Window

 Copy code hover
[image]

Data Types Displayed in Locals Window
Send feedback

The following is a list of data types and their default state when they are displayed in the Locals window.

Data Type | Default State
Currency | Value is displayed.
Double | Value is displayed.
Integer | Value is displayed
Long | Value is displayed.
Single | Value is displayed.
String | Value is displayed.
UDT | No value is displayed. Non-editable. Collapsed.
Variant | Value is displayed.
Object | No value is displayed. Non-editable. Collapsed.
Decimal | Value is displayed.
Array | No value is displayed. Non-editable. Collapsed.


Debug Menu

 Copy code hover
[image]

Debug Menu
Send feedback

Compile <project>

Step Into

Step Over

Step Out

Run To Cursor

Add Watch

Edit Watch

Quick Watch

Toggle Breakpoint

Clear All Breakpoints

Set Next Statement

Show Next Statement


Debugging Tab (Project Properties Dialog Box)

 Copy code hover
[image]

Debugging Tab (Project Properties Dialog Box)
Send feedback

Allows you to specify additional actions to be taken when the IDE goes into run mode. This feature is not available in Standard EXE projects — only in projects that can create ActiveX components such as User Controls, User Documents, and ActiveX Designers (such as webclasses and DHTML Pages). These components are typically consumed by client programs like Internet Explorer and this Debugging tab automates the process of launching these client programs for the Visual Basic developer.

Tab Options

When this project starts

Sets debugging options when your project starts.

Wait for components to be created

Tells Visual Basic to do nothing in run mode.

Start component

Lets the component determine what happens. The types of components include special ActiveX Designers like the DHTMLPage Designer and the Webclass Designer, and also User Controls and User Documents. If you select a User Control or User Document, Visual Basic will launch the browser and display a dummy test page that contains the component. The component can tell Visual Basic to either launch the browser with a URL or start another program.

Selecting a startup component on the Debugging tab does not affect the Startup Object specified on the General tab. For example, an ActiveX.dll project could specify

Copy code Copy code
Startup Object=Sub Main

and

Copy code Copy code
Start Component=DHTMLPage1

When the project runs, Visual Basic would register the DHTMLPage1 component, as well as other components, execute and then launch the Internet Explorer and navigate to a URL that creates an instance of DHTMLPage1.

Start program

Specifies an executable program to be used.

Start browser with URL

Specifies which URL the browser should navigate to.

Use existing browser

If Internet Explorer is already running, then use it. If not, launch a new browser.


Definition Command (Shortcut Menu)

 Copy code hover
[image]

Definition Command (Shortcut Menu)
Send feedback

Displays the location in the Code window where the variable or procedure under the pointer is defined. If the definition is in a referenced library, it is displayed in the Object Browser.


Definition Command (View Menu)

 Copy code hover
[image]

Definition Command (View Menu)
Send feedback

Displays the location in the Code window where the variable or procedure under the pointer is defined. If the definition is in a referenced library, it is displayed in the Object Browser.

Keyboard shortcut: SHIFT+F2.


Delete

 Copy code hover
[image]

Delete <item> Command (Shortcut Menu)
Send feedback

Deletes the selected item from the Toolbox. You can add the item again using the Additional Controls command on the shortcut menu.


Delete Page Command (Shortcut Menu)

 Copy code hover
[image]

Delete Page Command (Shortcut Menu)
Send feedback

Permanently deletes the selected page from the Toolbox.


Delete Watch Command (Shortcut Menu)

 Copy code hover
[image]

Delete Watch Command (Shortcut Menu)
Send feedback

Deletes the selected watch expression.


Design Mode and Exit Design Mode Commands (Run Menu)

 Copy code hover
[image]

Design Mode and Exit Design Mode Commands (Run Menu)
Send feedback

Turns design mode on and off per project. Design mode is the time during which no code from the project is running and events from the host or project will not execute. You can leave design mode by executing a macro or using the Immediate window.

Design Mode Command

Turns design mode on and changes to Exit Design Mode.

Exit Design Mode Command

Turns design mode off and clears all module level variables in the project.

Toolbar shortcut: .


Designers Tab (Components Dialog Box)

 Copy code hover
[image]

Designers Tab (Components Dialog Box)
Send feedback

Allows you to add designers to your project's Insert menu.

Note Note

This feature is not available in all versions of the Visual Basic Editor.

Tab Options

Available Designers List

Displays the available designers. You add a designer by selecting the check box next to its name.

Note Note

You can't remove a designer that is used in your project.

Path

Displays the path of the designer selected in the Available Designers List.

Selected Items Only

When selected, displays only those designers in the Available Designers list which you have selected to include in the project.

Apply

Adds the selected designers to the Insert menu without closing the dialog box.

OK

Adds the selected designers to the Insert menuand closes the Components dialog box.


Digital Signature Command (Tools Menu)

 Copy code hover
[image]

Digital Signature Command (Tools Menu)
Send feedback

Displays the Digital Signature dialog box where you can set the digital signature certificate for your project.


Digital Signature Dialog Box

 Copy code hover
[image]

Digital Signature Dialog Box
Send feedback

Allows you to digitally sign a project by assigning a certificate.

Dialog Box Options

The VBA project is currently signed as

Displays the name of the certificate that is currently assigned to the project.

Sign as

Displays the default certificate.

Remove

Removes the current certificate from the project.

Choose

Displays the Select Certificate dialog box, from which you can select a certificate.

OK

Assigns the selected certificate to the project and closes the Digital Signature dialog box.

Cancel

Closes the dialog box without changing the project's digital signature.


Dockable Command (Shortcut Menu)

 Copy code hover
[image]

Dockable Command (Shortcut Menu)
Send feedback

Toggles the ability to dock the active window on and off.

A window is docked when it is attached or "anchored" to one edge of the screen, application window, or another dockable window. When you move a dockable window, it "snaps" to the location. A window is not dockable when you can move it anywhere on the screen and leave it there.


Docking Tab (Options Dialog Box)

 Copy code hover
[image]

Docking Tab (Options Dialog Box)
Send feedback

Allows you to choose which windows you want to be dockable. A window is docked when it is attached or "anchored" to one edge of other dockable or application windows. When you move a dockable window, it "snaps" to the location. A window is not dockable when you can move it anywhere on the screen and leave it there.

Select the windows you want to be dockable and clear those that you do not. Any, none, or all of the windows in the list can be docked.


Edit Menu

 Copy code hover
[image]

Edit Menu
Send feedback

Undo

Redo

Cut

Copy

Paste

Clear and Delete

Select All

Find

Find Next

Replace

Indent

Outdent

List Properties/Methods

List Constants

Quick Info

Parameter Info

Complete Word

Bookmarks


Edit Watch Command (Debug Menu)

 Copy code hover
[image]

Edit Watch Command (Debug Menu)
Send feedback

Displays the Edit Watch dialog box in which you can edit or delete a watch expression. Available when the watch is set even if the Watch window is hidden.

Toolbar shortcut: . Keyboard shortcut: CTRL+W.


Edit Watch Dialog Box

 Copy code hover
[image]

Edit Watch Dialog Box
Send feedback

Use to delete or edit the context or type of a watch expression.

Important note Important

When selecting a context for a watch expression, use the narrowest scope that fits your needs. Selecting all procedures or all modules could slow down execution considerably, since the expression is evaluated after execution of each statement. Selecting a specific procedure for a context affects execution only while the procedure is in the list of active procedure calls.

Dialog Box Options

Expression

Displays the selected expression by default. The expression is a variable, a property, a function call, or any other valid expression. You may enter a different expression to evaluate.

Context

Sets the scope of the variables watched in the expression.

  • Procedure — Displays the procedure name where the selected term resides (default). Defines the procedure(s) in which the expression is evaluated. You may select all procedures or a specific procedure context in which to evaluate the variable.

  • Module — Displays the module name where the selected term resides (default). You may select all modules or a specific module context in which to evaluate the variable.

  • Project — Displays the name of the current project. Expressions can't be evaluated in a context outside of the current project.

Watch Type

Determines how Visual Basic responds to the watch expression.

  • Watch Expression — Displays the watch expression and its value in the Watch window. When you enter break mode, the value of the watch expression is automatically updated.

  • Break When Value Is True — Execution automatically enters break mode when the expression evaluates to true or is any nonzero value (not valid for string expressions).

  • Break When Value Changes — Execution automatically enters break mode when the value of expression changes within the specified context.

Delete

Deletes the watch expression.


Editor Format Tab (Options Dialog Box)

 Copy code hover
[image]

Editor Format Tab (Options Dialog Box)
Send feedback

Specifies the appearance of your Visual Basic code.

Tab Options

Code Colors

Determines the foreground and background colors used for the type of text selected in the list box.

  • Color Text List — Lists the text items that have customizable colors.

  • Foreground — Specifies the foreground color for the text selected in the Color Text List.

  • Background — Specifies the background color for text selected in the Color Text List

  • Indicator — Specifies the margin indicator color.

Font

Specifies the font used for all code.

Size

Specifies the size of the font used for code.

Margin Indicator Bar

Makes the margin indicator bar visible or invisible.

Sample

Displays sample text for the font, size, and color settings.


Editor Tab (Options Dialog Box)

 Copy code hover
[image]

Editor Tab (Options Dialog Box)
Send feedback

Specifies the Code window and Project window settings.

Tab Options

Code Settings

  • Auto Syntax Check — Determines whether Visual Basic should automatically verify correct syntax after you enter a line of code.

  • Require Variable Declaration — Determines whether explicit variable declarations are required in modules. Selecting this adds the Option Explicit statement to general declarations in any new module.

  • Auto List Member — Displays a list that contains information that would logically complete the statement at the current insertion point.

  • Auto Quick Info — Displays information about functions and their parameters as you type.

  • Auto Data Tips — Displays the value of the variable over which your cursor is placed. Available only in Break mode.

  • Auto Indent — Allows you to tab the first line of code; all subsequent lines will start at that tab location.

  • Tab Width — Sets the tab width, which can range from 1 to 32 spaces; the default is 4 spaces.

Window Settings

  • Drag-and-Drop Text Editing — Allows you to drag and drop elements within the current code and from the Code window into the Immediate or Watch windows.

  • Default to Full Module View — Sets the default state for new modules to allow you to look at procedures in the Code window either as a single scrollable list or only at one procedure at a time. It does not change the way currently open modules are viewed.

  • Procedure Separator — Allows you to display or hide separator bars that appear at the end of each procedure in the Code window.


Editor Toolbar

 Copy code hover
[image]

Editor Toolbar
Send feedback

Contains buttons that are shortcuts to some commonly used menu items. Frequently used when editing code.

You can click a toolbar button once to carry out the action represented by that button. You can select the Show ToolTips option in the General tab of the Options dialog box if you want to display ToolTips for the toolbar buttons.

Toolbar Buttons

List Properties/Methods

Opens a box in the code window that contains the properties and methods available for the object that precedes the period (.).

List Constants

Opens a box in the Code window that contains the constants that are valid choices for the property you typed and that precede the equals sign (=).

Quick Info

Provides the syntax for a variable, function, method, or procedure based on the location of your pointer within the name of the function, method, or procedure.

Parameter Info

Shows a popup in the Code window that contains information about the parameters of the function in which the pointer is located.

Complete Word

Accepts the characters that Visual Basic automatically adds to the word you are typing.

Indent

Shifts all lines in the selection to the next tab stop.

Outdent

Shifts all lines in the selection to the previous tab stop.

Toggle Breakpoint

Sets or removes a breakpoint at the current line.

Comment Block

Adds comment character to the beginning of each line of a selected block of text.

Uncomment Block

Removes the comment character from each line of a selected block of text.

Toggle Bookmark

Toggles a bookmark on or off for the active line in the Code window.

Next Bookmark

Moves the focus to the next bookmark in the bookmark stack.

Previous Bookmark

Moves the focus to the previous bookmark in the bookmark stack.

Clear All Bookmarks

Removes all bookmarks.


Export File Dialog Box

 Copy code hover
[image]

Export File Dialog Box
Send feedback

Allows you to give a name to the exported file and choose a location where it will be saved.

Dialog Box Options

Save in

Select the folder where you want to store the file.

Up One Level

Shows a list of folders or drives one level above the current folder.

Create New Folder

Creates a new folder.

Details

Shows the folder or documents in a list that includes the folder or document icon and name, its size (documents only), type, and the date and time it was last modified.

List

Shows the folders or documents in a list format that includes the folder or document icon and its name.

File name

Unless you specify a filename extension, Visual Basic automatically adds the default filename extension .frm for form, .bas for modules, or .cls for class modules.

List Files of Type

Select a file type from the list:

  • Form Files (*.frm) — Lists all forms.

  • Basic Files (*.bas) — Lists all standard modules.

  • Class Files (*.cis) — Lists all class modules.


File Command (Insert Menu)

 Copy code hover
[image]

File Command (Insert Menu)
Send feedback

Displays the Insert File dialog box so that you can insert text from an existing module at the current cursor position.

Not available when no editor is open.


File Menu

 Copy code hover
[image]

File Menu
Send feedback

New Project

Open Project

Save <host document> and Save As

Import File

Export File

Close Project

Remove <Item>

Print

Make <Project>

Close and Return to <host application>

Note Note

Some menu items are not available in all editions of the Visual Basic Editor.


Find Command (Edit Menu)

 Copy code hover
[image]

Find Command (Edit Menu)
Send feedback

Find

Searches for the specified text in a search range specified in the Find dialog box.

If a search is successful, the Find 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.

Toolbar shortcut: . Keyboard shortcut: CTRL+F.

Find Next

Finds and selects the next occurrence of the text specified in the Find What box of the Find dialog box.

Toolbar shortcut: . Keyboard shortcuts: SHIFT+F4 (Find Next) or SHIFT+F3 (Find Previous).

Dialog Box Options

Find What

Type or insert the information you want to find, or click the down arrow and select from the last four entries. If any text is selected or the cursor is on a word when you choose the command, this text is displayed in the Find What box.

Search

Specifies the search range.

  • Current Procedure — Searches only the current procedure.

  • Current Module — Searches only the current module.

  • Current Project — Searches all the modules in your project.

  • Selected Text — Searches a selected range of code in your project.

Direction

Sets the direction of the search to Down or Up from the location of the cursor, or All in the selected search range.

Find Whole Word Only

Searches for the full word by itself and not as part of a larger word.

Match Case

Finds all occurrences with the exact combination of uppercase and lowercase letters specified in the Find What box.

Use Pattern Matching

Searches using pattern-matching characters.

Find Next

Finds and selects the next occurrence of the text specified in the Find What box.

Cancel

Closes the dialog box without performing the search.

Replace

Displays the Replace dialog box, retaining the information typed in the Find What dialog box.


Find Whole Word Only Command (Object Browser Shortcut Menu)

 Copy code hover
[image]

Find Whole Word Only Command (Object Browser Shortcut Menu)
Send feedback

Allows you to search for occurrences that exactly match the word you typed into the Search Text box of the Object Browser.


Font Dialog Box

 Copy code hover
[image]

Font Dialog Box
Send feedback

Use to change the fonts, the font size, and/or the font style you use for text and data fields.

Dialog Box Options

Font

Lists all the fonts that you have installed for Windows. When the box first appears, the font already in use for the selected element is highlighted.

Font Style

Lists four additional attributes that you can assign to the font selected:

  • Regular — Standard, unmodified style

  • Bold — Boldface

  • Italic — Italic

  • Bold Italic — Bold Italic

Size

Lists common point sizes for the highlighted font. When the box first appears, the point size for the font already in use for the selected element is highlighted, and the highlighted point size appears in the edit box at the top.

You can select directly from the list or type the new point size in the edit box at the top (if you know that you have additional sizes installed for the currently selected printer or if you are using scalable type).

Effects

Lists two additional options that you can use for highlighting the selected font.

  • Strikeout — Prints the strikeout character across the font

  • Underline — Underlines the font You may select as many of the Effects as you wish.

Sample

Displays a sample of the font you have selected. The sample shows the font, style, size, effects, and color you have specified. You can use this box to preview the results as you experiment with different formatting options.

Script

Displays a list of available scripts.

OK

Applies the font changes to the selected report element.

Cancel

Cancels all font changes and leaves the selected element report unchanged.


Format Menu

 Copy code hover
[image]

Format Menu
Send feedback

Align

Make Same Size

Size to Fit

Size to Grid

Horizontal Spacing

Vertical Spacing

Center in Form

Arrange Buttons

Group

Ungroup

Order


General Tab (Options Dialog Box)

 Copy code hover
[image]

General Tab (Options Dialog Box)
Send feedback

Specifies the settings, error handling, and compile settings for your current Visual Basic project.

Tab Options

Form Grid Settings

Determines the appearance of the form when it is edited.

  • Show Grid — Determines whether to show the grid.

  • Grid Units — Displays the grid units used for the form.

  • Width — Determines the width of grid cells on a form (2 to 60 points).

  • Height — Determines the height of grid cells on a form (2 to 60 points).

  • Align Controls to Grid — Automatically positions the outer edges of controls on grid lines.

Show ToolTips

Displays ToolTips for the toolbar buttons.

Collapse Proj. Hides Windows

Determines whether the project, UserForm, object, or module windows are closed automatically when a project is collapsed in the Project Explorer.

Edit and Continue

  • Notify Before State Loss — Determines whether you will receive a message notifying you that the action requested will cause the all module level variables to be reset for a running project.

Error Trapping

Determines how errors are handled in the Visual Basic development environment. Setting this option affects all instances of Visual Basic started after you change the setting.

  • Break on All Errors — Any error causes the project to enter break mode, whether or not an error handler is active and whether or not the code is in a class module.

  • Break in Class Module — Any unhandled error produced in a class module causes the project to enter break mode at the line of code in the class module which produced the error.

  • Break on Unhandled Errors — If an error handler is active, the error is trapped without entering break mode. If there is no active error handler, the error causes the project to enter break mode. An unhandled error in a class module, however, causes the project to enter break mode on the line of code that invoked the offending procedure of the class.

Compile

  • Compile On Demand — Determines whether a project is fully compiled before it starts, or whether code is compiled as needed, allowing the application to start sooner.

  • Background Compile — Determines whether idle time is used during run time to finish compiling the project in the background. Background Compile can improve run time execution speed. This feature is not available unless Compile on Demand is also selected.


General Tab (Project Properties Dialog Box)

 Copy code hover
[image]

General Tab (Project Properties Dialog Box)
Send feedback

Specifies the settings for the current Visual Basic project. The name of the project is displayed in the title bar.

Tab Options

Project Name

Identifies your component in the Windows Registry and the Object Browser. It is important that it has a unique name.

The project name is the name of the type library for your component. The type library, or TypeLib, contains the description of the objects and interfaces provided by your component.

It is also used to qualify the names of classes. A combination of project name and class name is sometimes referred to as a fully qualified class name, or as a programmatic ID. The fully qualified class name may be required to correctly identify an object as belonging to your component.

Help File Name

Displays the name of the Help file associated with the project.

Project Description

Sets the descriptive text that is displayed in the Description pane at the bottom of the Object Browser.

Project Help Context ID

Lists the context ID for the specific Help topic to be called when the user selects the [image] button while the application's object library is selected in the Object Browser.

Conditional Compilation Arguments

Lists the constant declarations used for conditional compilation.


Global Keys

 Copy code hover
[image]

Global Keys
Send feedback

Use these key combinations in all Visual Basic windows:

Press | To
F5 | Run a Sub/UserForm or macro.
F8 | Execute code one line at a time.
SHIFT+F8 | Execute statements one line at a time without stepping into procedure calls.
CTRL+BREAK | Stop running a Visual Basic application.
CTRL+G | Displays the Immediate window.
CTRL+TAB | Switch between windows.
ALT+F5 | Runs the error handler code or returns the error to the calling procedure. Does not affect the setting for error trapping on the General tab of the Options dialog box.
ALT+F8 | Steps into the error handler or returns the error to the calling procedure. Does not affect the setting for error trapping on the General tab of the Options dialog box.

Use these key combinations in all Windows-based applications:

Press | To
F1 | Open Help.
ALT+F6 | Toggle between the last two active windows.
ALT+F4 | (Visual Basic) Close the active window; if all windows are closed, close Visual Basic.
CTRL+C or F3 | 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.
SHIFT+F10 | View shortcut menu.


Group and Ungroup Commands (Format Menu)

 Copy code hover
[image]

Group and Ungroup Commands (Format Menu)
Send feedback

Groups and ungroups selected objects.

Group

Creates a group.

Note Note

You can still select a single object from within a group and change its properties.
Note Note

You cannot create groups within a group (nested grouping).

Toolbar shortcut: .

Ungroup

Ungroups the objects that were previously grouped.

Toolbar shortcut: .


Group Members Command (Object Browser Shortcut Menu)

 Copy code hover
[image]

Group Members Command (Object Browser Shortcut Menu)
Send feedback

Toggles the Members of pane between an alphabetical list of the members of the selected class and a list grouped by the member type.


Help Command (Shortcut Menu)

 Copy code hover
[image]

Help Command (Shortcut Menu)
Send feedback

Displays the Help topic related to the item selected when the Help command is chosen.


Help Menu

 Copy code hover
[image]

Help Menu
Send feedback

Microsoft Visual Basic for Applications Help

Displays the help viewer for the associated application.

Toolbar shortcut: . Keyboard shortcut: F1.

MSDN on the Web

Connects you to the Internet where you can get additional information and support.

To use this command, you must have a network connection to the Internet and a browser.

About Microsoft Visual Basic for Applications

Displays a dialog box with the version number, a copyright notice, and system information.

Microsoft Visual Basic for Applications Help

Displays the help viewer for the associated application.

Toolbar shortcut: . Keyboard shortcut: F1.

MSDN on the Web

Connects you to the Internet where you can get additional information and support.

To use this command, you must have a network connection to the Internet and a browser.

About Microsoft Visual Basic for Applications

Displays a dialog box with the version number, a copyright notice, and system information.


Hide Command (Shortcut Menu)

 Copy code hover
[image]

Hide Command (Shortcut Menu)
Send feedback

Hides the active window, project, folder, module, or the Toolbox.


Horizontal Spacing Commands (Format Menu)

 Copy code hover
[image]

Horizontal Spacing Commands (Format Menu)
Send feedback

Changes the horizontal space between selected objects.

Make Equal

Moves the selected objects so that there is equal space between them using the outermost objects as endpoints. The outermost objects do not move.

Toolbar shortcut: .

Increase

Increases horizontal spacing by one grid unit based on the object with focus. When an object has focus, white handles appear on its borders. You can change the size of your grid units in the General tab of the Options dialog box.

Toolbar shortcut: .

Decrease

Decreases horizontal spacing by one grid unit based on the object with focus. When an object has focus, white handles appear on its borders. You can change the size of your grid units in the General tab of the Options dialog box.

Toolbar shortcut: .

Remove

Removes the horizontal space so that the objects are aligned with their edges touching based on the object with focus. When an object has focus, white handles appear on its borders.

Toolbar shortcut: .

Note Note

The object with focus does not move but the other objects move around it.
Note Note

If using the Horizontal Spacing command does not produce the results you want, try to manually rearrange some of the objects and repeat the command. Also, try the using the Vertical Spacing command.


Immediate Window

 Copy code hover
[image]

Immediate Window
Send feedback

Allows you to:

  • Type or paste a line of code and press ENTER to run it.

  • Copy and paste the code from the Immediate window into the Code window but does not allow you to save code in the Immediate window.

The Immediate window can be dragged and positioned anywhere on your screen unless you have made it a dockable window from the Docking Tab of the Options dialog box.

You can close the window by clicking the Close box. If the Close box is not visible, double-click the Title bar to make the Close box visible, then click it.

Note Note

In break mode, a statement in the Immediate window is executed in the context or scope that is displayed in the Procedure box. For example, if you type Print variablename, your output is the value of a local variable. This is the same as if the Print method had occurred in the procedure you were executing when the program halted.


Immediate Window Command (View Menu)

 Copy code hover
[image]

Immediate Window Command (View Menu)
Send feedback

Displays the Immediate window and displays information resulting from debugging statements in your code or from commands typed directly into the window.

Use the Immediate window to:

  • Test problematic or newly written code.

  • Query or change the value of a variable while running an application. While execution is halted, assign the variable a new value as you would in code.

  • Query or change a property value while running an application.

  • Call procedures as you would in code.

  • View debugging output while the program is running.

Toolbar shortcut: . Keyboard shortcut: CTRL+G.


Immediate Window Keyboard Shortcuts

 Copy code hover
[image]

Immediate Window Keyboard Shortcuts
Send feedback

Use these key combinations in the Immediate window:

Press | To
ENTER | Run a line of selected code.
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 Call Stack dialog box (break mode only).
F5 | Continue running an application.
F8 | Execute code one line at a time (single step).
SHIFT+F8 | Execute code one procedure at a time (procedure step).
DELETE or DEL | Delete the selected text without placing it on the Clipboard.
F2 | Display the Object Browser.
CTRL+ENTER | Insert carriage return.
CTRL+HOME | Move the cursor to the top of the Immediate window.
CTRL+END | Move the cursor to the end of the Immediate window.
SHIFT+F10 | View shortcut menu.
ALT+F5 | Runs the error handler code or returns the error to the calling procedure. Does not affect the setting for error trapping on the General tab of the Options dialog box.
ALT+F8 | Steps into the error handler or returns the error to the calling procedure. Does not affect the setting for error trapping on the General tab of the Options dialog box.


Import File and Export File Commands (File Menu)

 Copy code hover
[image]

Import File and Export File Commands (File Menu)
Send feedback

Adds existing modules and forms to your project or saves a module or form as a separate file.

Import File

Displays the Import Files dialog box which allows you to add an existing module or form to the project. A copy of the file is added to the project and the original file is left intact. If you import a form or module with the same name as an existing one, the file is added with a number appended to it.

Imported components appear in the Project Explorer window.

Toolbar shortcut: . Keyboard shortcut: CTRL+M.

Export File

Displays the Export File dialog box so that you can extract the active form or module from the project. The file is copied into an external file.

Not available if you have not selected a file in the Project Explorer.

Toolbar shortcut: . Keyboard shortcut: CTRL+E.


Import File Dialog Box

 Copy code hover
[image]

Import File Dialog Box
Send feedback

Allows you to choose the file that you want to import.

Dialog Box Options

Look in

Select the location of the project you want to open.

Up One Level

Shows a list of folders or drives one level above the current folder.

Create New Folder

Creates a new folder.

List

Shows the folders or projects in a list format that includes the folder or project icon and its name.

Details

Shows the folders or projects in a list that includes the folder or project icon and name, its size, type, and the date and time it was last modified.

Filename

Select or type the name of the file you want to import.

List Files of Type

Select a file type; the default is Visual Basic Project Files (*.frm, *.bas, *.cls). Files of the selected type will appear in the File Name list box.

Open

Opens the selected file.

Cancel

Closes the dialog box without opening a new project.


Import Page and Export Page Commands (Shortcut Menu)

 Copy code hover
[image]

Import Page and Export Page Commands (Shortcut Menu)
Send feedback

Imports and exports pages.

Import Page

Opens the Import Page dialog box so that you can find and select the page you want to add to the Toolbox.

The Import Page dialog box is the Windows Open common dialog box.

Export Page

Opens the Export Page dialog box so that you can select a location and name for the selected page that you want to export from the Toolbox.

The Export Page dialog box is the same as the Windows Save common dialog box.


Indent Command (Edit Menu)

 Copy code hover
[image]

Indent Command (Edit Menu)
Send feedback

Shifts all lines in the selection to the next tab stop. If you place the cursor anywhere in a line and choose the Indent command, the entire line is shifted to the next tab stop. All lines in the selection are moved the same number of spaces to retain the same relative indentation within the selected block.

You can change the tab width on the Editor tab of the Options dialog box.

Toolbar shortcut: . Keyboard shortcuts: CTRL+M.


Insert File Dialog Box

 Copy code hover
[image]

Insert File Dialog Box
Send feedback

Allows you to look for and insert a file into a module in your project.

Dialog Box Options

Look in

Displays the computers, servers, drives, and folders available on your computer that you can use to locate the project you want to open.

Up One Level

Shows a list of folders or drives one level above the current server, computer, or folder.

Create New Folder

Creates a new folder.

List

Shows the folders or documents in a list format that includes the folder or document icon and its name.

Details

Shows the folder or documents in a list that includes the folder or document icon and name, its size (documents only), type, and the date and time it was last modified.

File Name

Selector type the name of the file you want to insert.

List Files of Type

Select a file type; the default is Text Files (*.txt). Files of the selected type will appear in the File Name box.

Open

Inserts the selected file.

Desktop

Lists the folders and files on the desktop. The files and folders are displayed in the File Name box.

Cancel

Closes the dialog box without inserting a new file.


Insert Menu

 Copy code hover
[image]

Insert Menu
Send feedback

Procedure

UserForm

Module

Class Module

Components

File

Note Note

Some menu items are not available in all editions of the Visual Basic Editor.


Last Position Command (View Menu)

 Copy code hover
[image]

Last Position Command (View Menu)
Send feedback

Allows you to quickly navigate to a previous location in your code. Enabled only if you edited code or made a Definition command call and only when the Code window is displayed. Visual Basic only keeps track of the last 8 lines that were accessed or edited.

Keyboard shortcut: CTRL+SHIFT+F2.


Load Picture, Load Icon Dialog Boxes

 Copy code hover
[image]

Load Picture, Load Icon Dialog Boxes
Send feedback

Loads an existing picture file.

Dialog Box Options

Look in

Select the location of the picture you want to open.

Up One Level

Shows a list of folders or drives one level above the current folder.

Create New Folder

Creates a new folder.

List

Shows the folders or files in a list format that includes the icon and its name.

Details

Shows the folders or files in a list that includes the icon and name, its size, type, and the date and time it was last modified.

File name

Select or type the name of a picture file you want to open.

List files of type

Select a file type. Files of the selected type appear in the File Name box.

  • All Picture Files (*.bmp, *.dib, *.wmf, *.emf, *.ico, *.cur) — Lists all picture files.

  • Bitmaps (*.bmp, *.dib) — Lists bitmaps and DIBs.

  • Metafiles (*.wmf, *.wmf) — Lists Microsoft Windows Metafiles.

  • Icons (*.ico, *.cur) — Lists the icons.

  • All Files (*.*) — Lists files of all types.

Open

Opens the selected file.

Cancel

Closes the dialog box without loading a picture file.

Desktop

Lists the folders and files on the desktop. The files and folders are displayed in the File Name box.


Locals Window

 Copy code hover
[image]

Locals Window
Send feedback

Automatically displays all of the declared variables in the current procedure and their values.

When the Locals window is visible, it is automatically updated every time there is a change from Run to Break mode or you navigate in the stack display.

You can:

  • Resize the column headers by dragging the border to the right or the left.

  • Close the window by clicking the Close box. If the Close box is not visible, double-click the Title bar to make the Close box visible, then click it.

Window Elements

Calls Stack Button

Opens the Call Stack dialog box which lists the procedures in the call stack.

Expression

Lists the name of the variables.

The first variable in the list is a special module variable and can be expanded to display all module level variables in the current module. For a class module, the system variable <Me> is defined. For standard modules, the first variable is the is defined. For standard modules, the first variable is the <name of the current module> . Global variables and variables in other projects are not accessible from the Locals window.

You cannot edit data in this column.

Value

List the value of the variable.

When you click on a value in the Value column, the cursor changes to an I-beam. You can edit a value and then press ENTER, the UP ARROW key, the DOWN ARROW key, TAB, SHIFT+TAB, or click on the screen to validate the change. If the value is illegal, the Edit field remains active and the value is highlighted. A message box describing the error also appears. Cancel a change by pressing ESC.

All numeric variables must have a value listed. String variables can have an empty Value list.

Variables that contain subvariables can be expanded and collapsed. Collapsed variables do not display a value but each subvariable does. The expand icon, [image] and the collapse icon, [image] appear to the left of the variable.

Type

Lists the variable type. You cannot edit data in this column.


Locals Window Command (View Menu)

 Copy code hover
[image]

Locals Window Command (View Menu)
Send feedback

Displays the Locals window and automatically displays all of the variables in the current stack and their values.

The Locals window is automatically updated every time you change from run time to break mode and every time the stack context changes.

Toolbar shortcut: .


Macros Command (Tools Menu)

 Copy code hover
[image]

Macros Command (Tools Menu)
Send feedback

Displays the Macros dialog box where you can create, run, step into, edit, or delete a macro.


Macros Dialog Box

 Copy code hover
[image]

Macros Dialog Box
Send feedback

Allows you to run, edit, or delete the selected macro. You can also create a macro from the Macros dialog box.

Dialog Box Options

Macro Name

Contains the name of the selected macro or is blank if there are no macros in the Macro Box.

Macro Box

Lists the available macros in the Project selected in the Macros In box.

Macros In

Lists the available projects.

Run

Runs the selected macro.

Step Into

Highlights the first line of the macro and places the Current Execution Line Indicator.

Edit

Opens the Code window with the selected macro visible so you can modify your macro.

Create

Opens a module in the Code window so you can create a new macro.

Delete

Removes the selected macro from your project.


Make

 Copy code hover
[image]

Make <Project> Command (File Menu)
Send feedback

Opens the Make Project dialog box so that you can build your project into a DLL.

Note Note

This feature is not available in all versions of the Visual Basic Editor.


Make Same Size Commands (Format Menu)

 Copy code hover
[image]

Make Same Size Commands (Format Menu)
Send feedback

Based on the object with the white grab handles, makes the selected objects the same size in the dimension you select.

Width

Adjusts width.

Toolbar shortcut: .

Height

Adjusts height.

Toolbar shortcut: .

Both

Adjusts both the width and the height.

Toolbar shortcut: .


Make Tab (Project Properties Dialog Box)

 Copy code hover
[image]

Make Tab (Project Properties Dialog Box)
Send feedback

Note Note

This feature is not available in all versions of the Visual Basic Editor.

Sets the attributes for the executable file you make. Displays the name of the current project in the title so you can determine which project will be affected by any changes you make. The current project is the item currently selected in the Project Explorer.

Tab Options

Version Number

Creates the version number for the project.

  • Major — Major release number of the project; 0 - 9999.

  • Minor — Minor release number of the project; 0 - 9999.

  • Revision — Revision version number of the project; 0-9999.

  • Auto Increment — If selected, automatically increases the Revision number by one each time you run the Make Project command for this project.

Version Information

Lets you provide specific information about the current version of your project.

  • Type — Information you can use to set a value. You can enter information for your company name, file description, legal copyright, legal trademarks, product name and comments.

  • Value — The value for the type of information selected in the Type box.

DLL Base Address

Allows you to set the base address

Remove information about unused ActiveX Controls

Allows you to specify that even if a control is unused (present in the Toolbox, but not referenced in code), its information will be retained. Uncheck this when you plan to dynamically add the referenced control at run time using the Controls collection's Add method.


Margin Indicators

 Copy code hover
[image]

Margin Indicators
Send feedback

Visual Basic contains margin indicators that provide visual cues to certain actions during the editing of your code. If more than one action occurs on a line, the appropriate indicators also appear.

The margin indicators appear in the Margin Indicator bar on left side of the Code window.

You can turn the Margin Indicator Bar on and off in the Editor Format tab of the Options dialog box.

Margin Indicator | Margin Indicator Name | Description
 | Breakpoint | Indicates that you have set a breakpoint using the Toggle Breakpoint command on the Debug menu. You can toggle the breakpoint by placing your mouse pointer in the margin indicator region and clicking.
 | Current line of execution | Indicates the line of code that will be executed next. You can drag this margin indicator to a new location within any running code module. If you drag the Current line of execution margin indicator to any non-valid region or line, nothing happens and the indicator returns to the original location.
 | Bookmark | Indicates the location of a bookmark set using the Toggle Bookmark command on the Edit menu.
 | Call Stack Marker | Indicates lines that are currently in the call stack. The Call Stack Marker indicator appears only in break mode.


Member Options Dialog Box

 Copy code hover
[image]

Member Options Dialog Box
Send feedback

Allows you to add Help information or comments about the procedures, that you define in your project.

Dialog Box Options

Member Name

Displays the name of the item selected in the Classes or the Members of list.

Description

Allows you to specify a string that shows up in the Details pane of the Object Browser.

Help File

Displays the Help file associated with the item listed in the Member Name box. This is set in the Help File Name box in the General tab of the Project Properties dialog box.

Help Context ID

Assigns a unique numeric value for the context ID. This value is used to find the appropriate Help topic in the file listed in the Help File box when the user presses F1 or the [image] button while looking at the procedure in the Object Browser.


Menu Shortcut Keys Available in the Code Window

 Copy code hover
[image]

Menu Shortcut Keys Available in the Code Window
Send feedback

Use these key combinations for menu shortcuts in the Code window:

Press | To
CTRL+P | Print
CTRL+Z | Undo
CTRL+V | Paste
DEL or DELETE | Delete
CTRL+F | Find
SHIFT+F4 | Find Next
CTRL+H | Replace
TAB | Indent
SHIFT+TAB | Outdent
SHIFT+F2 | Definition
CTRL+SHIFT+F2 | Last Position
F2 | Object Browser
CTRL+G | Immediate Window
CTRL+R | Project Explorer
F4 | Properties Window
F8 | Step Into
SHIFT+F8 | Step Over
CTRL+F8 | Run To Cursor
F9 | Toggle Breakpoint.
CTRL+SHIFT+F9 | Clear All Breakpoints
F5 | Run Sub/Form or Run Macro
CTRL+BREAK | Break
SHIFT+F10 | Shortcut menu
CTRL+J | List Properties/Methods
CTRL+SHIFT+J | List Constants
SHIFT+F9 | Quick Watch
CTRL+M | ImportFile
CTRL+E | Export File
CTRL+I | Quick Info
CTRL+SHIFT+I | Parameter Info
CTRL+SPACEBAR | Complete Word


Module and Class Module Commands (Insert Menu)

 Copy code hover
[image]

Module and Class Module Commands (Insert Menu)
Send feedback

Module

Inserts a new standard module and adds it to your active project.

Toolbar shortcut: .

Class Module

Creates a new class module and adds it to your active project.

Toolbar shortcut: .


Move Command (Shortcut Menu)

 Copy code hover
[image]

Move Command (Shortcut Menu)
Send feedback

Depending on whether a window or the Toolbox is active when you select the Move command, one of the following actions occurs:

  • Changes the pointer to a [image] so you can move the active window to another location.

  • Displays the Page Order dialog box where you can change the order of the pages in your Toolbox.

You can move the selected page to the left or right of the other pages.


New Page Command (Shortcut Menu)

 Copy code hover
[image]

New Page Command (Shortcut Menu)
Send feedback

Adds a new tabbed page with the name, New Page. You can use the Rename command on the shortcut menu to change it.

You can have more than one page with the name, New Page.

When you add a new page to the Toolbox, the page automatically contains the Pointer tool.


New Project Command (File Menu)

 Copy code hover
[image]

New Project Command (File Menu)
Send feedback

Displays the New Project dialog box where you choose the type of project you want to create.

If there is currently another project open when you create a new project, you will be prompted to save your work.

Available only at design time.

Note Note

This feature is not available in all versions of the Visual Basic Editor.


New Project Dialog Box

 Copy code hover
[image]

New Project Dialog Box
Send feedback

Allows you to select the type of project you want to create. If there is currently another project open, you will be asked to save any changes before the new project created.

Dialog Box Options

List of projects

Displays the valid projects that you can add.


New Toolbar Dialog Box

 Copy code hover
[image]

New Toolbar Dialog Box
Send feedback

Allows you to give your new toolbar a name.

Dialog Box Option

Toolbar name

You can type the name for your new toolbar or use the default name. The default name changes for each custom toolbar, for example, Custom1, Custom2 and so on.


Object Browser

 Copy code hover
[image]

Object Browser
Send feedback

Displays the classes, properties, methods, events, and constants available from object libraries and the procedures in your project. You can use it to find and use objects you create, as well as objects from other applications.

You can get Help for the Object Browser by searching for Object Browser in Help.

Window Elements Project/Library Box

Displays the currently referenced libraries for the active project. You can add libraries in the References dialog box. <All Libraries> allows all of the libraries to be displayed at one time.

Search Text Box

Contains the string that you want to use in your search. You can type or choose the string you want. The Search Text box contains the last 4 search strings that you entered until you close the project. You can use the standard Visual Basic wildcards when typing a string.

If you want to search for a whole word, you can use the Find Whole Word Only command from the shortcut menu.

Go Back Button

Allows you to go back to the previous selection in the Classes and Members of lists. Each time you click it you move back one selection until all of your choices are exhausted.

Go Forward Button

Allows you to repeat your original selections in the Classes and Members of lists each time you click it, until you exhaust the list of selections.

Copy to Clipboard Button

Copies the current selection in the Members of list or the Details pane text to the Clipboard. You can then paste the selection into your code.

View Definition Button

Moves the cursor to the place in the Code window where the selection in the Members of list or the Classes list is defined.

Help Button

Displays the online Help topic for the item selected in the Classes or the Members of list. You can also use F1.

Search Button

Initiates a search of the libraries for the class or property, method, event or constant that matches the string you typed in the Search Text box, and opens the Search Results pane with the appropriate list of information.

Show/Hide Search Results Button

Opens or hides the Search Results pane. The Search Results pane changes to show the search results from the project or library chosen in the Project/Library list. Search results are listed alphabetically from A to Z.

Search Results List

Displays the library, class, and member that corresponds to the items that contain your search string. The Search Results pane changes when you change the selection in the Project/Library box.

Classes List

Displays all of the available classes in the library or project selected in the Project/Libraries box. If there is code written for a class, that class appears in bold. The list always begins with <globals>, a list of globally accessible members.

If you select a Class and do not specify a member, you will get the default member if one is available. The default member is identified by an asterisk (*) or by the default icon specific to the member.

Members of List

Displays the elements of the class selected in the Classes pane by group and then alphabetically within each group. Methods, properties, events, or constants that have code written for them appear bold. You can change the order of this list with the Group Members command on the Object Browser shortcut menu.

Details Pane

Shows the definition of the member. The Details pane contains a jump to the class or library to which the element belongs. Some members have jumps to their parent class. For example, if the text in the Details pane states that Command1 is declared as a command button type, clicking on command button takes you to the Command Button class.

You can copy or drag text from the Details pane to the Code window.

Split Bar

Splits the panes so that you can adjust their size. There are splits between the:

  • Classes box and the Members of box.

  • Search Results list and the Classes and Members of boxes.

  • Classes and Members of boxes and the Details pane.


Object Browser Command (View Menu)

 Copy code hover
[image]

Object Browser Command (View Menu)
Send feedback

Displays the Object Browser, which lists the object libraries, the type libraries, classes, methods, properties, events, and constants you can use in code, as well as the modules and procedures you defined for your project.

Toolbar shortcut: . Keyboard shortcut: F2.


Object Command (View Menu)

 Copy code hover
[image]

Object Command (View Menu)
Send feedback

Displays the active item.

Toolbar shortcut: . Keyboard shortcut: SHIFT+F7.


Open Project Command (File Menu)

 Copy code hover
[image]

Open Project Command (File Menu)
Send feedback

Closes the current project or group project, if one is loaded, and opens an existing project or group of projects.

You can open as many projects as your system resources permit.

Toolbar shortcut: . Keyboard shortcut: CTRL+O.


Open Project Dialog Box

 Copy code hover
[image]

Open Project Dialog Box
Send feedback

Lets you locate and open a standalone project.

Dialog Box Options

Open

Displays the selected file.

Cancel

Closes the dialog box without opening a new project.


Options Command (Tools Menu)

 Copy code hover
[image]

Options Command (Tools Menu)
Send feedback

Displays the Options dialog box, from which you can choose a tab to set attributes of the Visual Basic programming environment.

Tabs

  • Editor

  • Editor Format

  • General

  • Docking


Options Dialog Box

 Copy code hover
[image]

Options Dialog Box
Send feedback

Allows you to change default settings for the Visual Basic development environment.

The Options dialog box has the following tabs:

  • Editor

  • Editor Format

  • General

  • Docking


Options Tab (Customize Dialog Box)

 Copy code hover
[image]

Options Tab (Customize Dialog Box)
Send feedback

Allows you to change the appearance of your menu bar and toolbars.

Tab Options

Large Icons

Changes the toolbar icons to a larger size.

Show ScreenTips on toolbars

Turns ScreenTips off and on.

Show shortcut keys in ScreenTips

Displays the shortcut keys on the menus.

Menu animations

Lists available animations you can apply to your menu bar.


Order Commands (Format Menu)

 Copy code hover
[image]

Order Commands (Format Menu)
Send feedback

Changes the order of the selected objects on a form.

Bring To Front

Moves the selected objects to the front of all other objects on a form.

Toolbar shortcut: . Keyboard shortcut: CTRL+J.

Send To Back

Moves the selected objects behind all other objects on a form.

Toolbar shortcut: . Keyboard shortcut: CTRL+K.

Bring Forward

Moves the selected object one step higher in the z-order.

Toolbar shortcut: .

Send Backward

Moves the selected object one step lower in the z-order.

Toolbar shortcut: .


Outdent Command (Edit Menu)

 Copy code hover
[image]

Outdent Command (Edit Menu)
Send feedback

Shifts all lines in the selection to the previous tab stop. If you place the cursor anywhere in a line and choose the Outdent command, the entire line is shifted to the previous tab stop. All lines in the selection are moved the same number of spaces to retain the same relative indentation within the selected block.

You can change the tab width on the Editor tab of the Options dialog box.

Toolbar shortcut: . Keyboard shortcuts: CTRL+SHIFT+M.


Page Order Dialog Box

 Copy code hover
[image]

Page Order Dialog Box
Send feedback

AllowSAs you to change the order of your tabbed pages.

Dialog Box Options

Page Order

Lists the tabbed pages in order from the left to the right.

Move Up

Moves the selected page up one place in the list each time you click it.

Move Down

Moves the selected page down one place in the list each time you click it.


Parameter Info Command (Edit Menu)

 Copy code hover
[image]

Parameter Info Command (Edit Menu)
Send feedback

Shows a popup in the Code window that contains information about the parameters of the initial function or statement. If you have a function or statement that contains functions as its parameters, choosing Parameter Info provides information about the first function. Quick Info provides information about each embedded function.

As you type a parameter it is bold until you type the comma used to delineate it from the next parameter.

The Parameter Info, once activated, will not close until:

  • All of the required parameters are entered.

  • The function is ended without using all of the optional parameters.

  • You press ESC.

Toolbar shortcut: . Keyboard shortcut: CTRL+SHIFT+I.


Print Command (File Menu)

 Copy code hover
[image]

Print Command (File Menu)
Send feedback

Prints forms and code to the printer specified in the Microsoft Windows Control Panel.

Toolbar shortcut: . Keyboard shortcut: CTRL+P.

Dialog Box Options

Printer

Identifies the printer to which you are printing.

Range

Determines the range you print:

  • Selection — Prints the currently selected code.

  • Current Module — Prints the forms and/or code for the currently selected module.

  • Current Project — Prints the forms and/or code for the entire project.

Print What

Determines what you print. You can select as many options as you like, depending on what you selected as the Range.

  • Form Image — Prints the form images.

  • Code — Prints the code for the selected range.

Print Quality

Determines whether you print high, medium, low, or draft output quality.

Print to File

If selected, print is sent to the file specified in the Print To File dialog box. This dialog box appears after you choose OK in the Print dialog box.

OK

Prints your selection.

Cancel

Closes the dialog box without printing.

Setup

Displays the standard Print Setup dialog box.


Print Setup Dialog Box

 Copy code hover
[image]

Print Setup Dialog Box
Send feedback

Appears whenever you select Setup from the Print dialog box.

Use the Print Setup dialog box to select the printer, page orientation, and paper size.

Dialog box options

Printer

Allows you to specify the printer. If you don't select a printer, Visual Basic will print to the Windows default printer.

  • Name — Displays a list of available printers.

  • Status — Displays the status of the printer and whether it is ready to print.

  • Type — Displays the type of printer.

  • Where — Displays the location of the printer. If the printer is on a network, displays the path to the server.

  • Comment — Displays the physical location of the printer and additional information.

  • Properties — Opens the Properties dialog box specific to the printer where you can choose additional options such as paper and the way graphics are printed.

Paper

Allows you to select the paper size and source (from among those available for the printer). The sizes and sources available depend on the printer you have selected and they change when you change printers.

  • Size — Displays a list of the available paper sizes.

  • Source — Displays the available source of paper for the printer you choose.

Orientation

Allows you to specify whether the program is to print in Portrait or Landscape orientation.


Procedure Command (Insert Menu)

 Copy code hover
[image]

Procedure Command (Insert Menu)
Send feedback

Inserts a new Sub, Function, or Property procedure into the active module.

Not available if the module is not active.

Toolbar shortcut: .


Project Explorer

 Copy code hover
[image]

Project Explorer
Send feedback

Displays a hierarchical list of the projects and all of the items contained in and referenced by each of the projects.

Window Elements

View Code

Displays the Code window so you can write and edit code associated with the selected item.

View Object

Displays the Object window for the selected item, an existing Document or UserForm.

Toggle Folders

Hides and shows the object folders while still showing the individual items contained within them.

List window

Lists the all loaded projects and the items included in each project.

  • Project.

    The project and items contained within it.

    • UserForms [image] All .frm files associated with the project.

    • Document The document associated with the project. For example, in Microsoft Word, it is the Word document.

    • Modules [image] All .bas modules for the project.

    • Class Modules [image] All .cls files for the project.

    • ActiveX Designers [image] All designers, .dsr files, in the project.

    • References [image] References to other projects that you have set using the References command on the Tools menu.


Project Properties Dialog Box

 Copy code hover
[image]

Project Properties Dialog Box
Send feedback

Specifies the settings for a specific project.


Properties Command (Object Browser Shortcut Menu)

 Copy code hover
[image]

Properties Command (Object Browser Shortcut Menu)
Send feedback

Displays the Member Options dialog box where you type a description of the custom member and give it a Help Context ID and Help File name.

Only available for items containing Basic code.


Properties Command (Shortcut Menu)

 Copy code hover
[image]

Properties Command (Shortcut Menu)
Send feedback

Opens the Properties window for the selected item.


Properties Window

 Copy code hover
[image]

Properties Window
Send feedback

Lists the design-time properties for selected objects and their current settings. You can change these properties at design time. When you select multiple controls, the Properties window contains a list of the properties common to all the selected controls.

Window Elements

Object Box

Lists the currently selected object. Only objects from the active form are visible. If you select multiple objects, the properties common to the objects and their settings, based on the first object selected, appear on the Properties List tabs.

Properties List Tabs

  • Alphabetic Tab — Alphabetically lists all properties for the selected object that can be changed at design time, as well as their current settings. You can change the property setting by selecting the property name and typing or selecting the new setting.

  • Categorized Tab — Lists all properties for the selected object by category. For example, BackColor, Caption, and ForeColor are in the Appearance category. You can collapse the list so that you see the categories or you can expand a category to see the properties. When you expand or collapse the list, you see a plus (+) icon or minus (-) icon to the left of the category name.


Properties Window Command (View Menu)

 Copy code hover
[image]

Properties Window Command (View Menu)
Send feedback

Displays the Properties window, which lists the design-time properties for a selected form, control, class, project or module.

Toolbar shortcut: . Keyboard shortcut: F6.


Properties Window Keyboard Shortcuts

 Copy code hover
[image]

Properties Window Keyboard Shortcuts
Send feedback

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

Press | To
PAGE DOWN | Move down through the Property list.
PAGE UP | Move up through the Property list.
DOWN ARROW | Move down through the Property list, one property at a time.
UP ARROW | Move up through the Property list, one property at a time.
RIGHT ARROW | Move down through the Property list, one property at a time.
LEFT ARROW | Move up through the Property list, one property at a time.
END | Move to the last property in the list.
HOME | Move to the first property in the list.
TAB | Move the insertion point among the property, properties settings box, and the Object 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 switch focus to the settings box for other property types.
ALT+F6 | Switch between the last two active windows.

Use these key combinations when the settings box for a property has the focus in the Properties window:

Press | To
CTRL+Z | Undo the last editing action in the current line.
CTRL+C | Copy the selected text to the Clipboard.
CTRL+X | Cut the selected text to the Clipboard.
DEL or DELETE | Delete the selected text without placing it on the Clipboard.
CTRL+V | Paste the Clipboard contents at the insertion point.
SHIFT+TAB | Switch focus between the Object box and the active Properties tab.
TAB | Move the focus among the Object box, the active Properties tab, a property, and the property value.
ESC | Cancel the property change.
CTRL +SHIFT+ALPHA | Move to the next property that begins with the alpha character, in the list.

Use these key combinations when a property has enumerated values and its settings box has the focus in the Properties window:

Press | To
ALT+DOWN ARROW | Open the settings box list.
ALT+UP ARROW | Close the settings box list.

Use these key combinations when you set the BackColor, ForeColor, FillColor, or BorderColor properties, and the settings box has the focus in the Properties window:

Press | To
ALT+DOWN ARROW | Display the Color palette.
ALT+UP ARROW | Close the Color palette.

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.


Protection Tab (Project Properties Dialog Box)

 Copy code hover
[image]

Protection Tab (Project Properties Dialog Box)
Send feedback

Sets the protection for your project.

Dialog Box Options

Lock Project

Provides a way to lock your project and prevent someone from changing it.

  • Lock project for viewing — Locks the project so that it cannot be viewed or edited.

Password to view project properties

Sets the passwords that allow someone to view the project properties.

  • Password — Sets the password for the project. If you do not check the Lock Project for Viewing option but set a password, you will be required to enter a password to open the Property window the next time you open the project.

  • Confirm password — Confirms the password typed in the Password box. The contents of the Confirm Password box and the Password box must match when you press OK or you get an error.


Quick Info Command (Edit Menu)

 Copy code hover
[image]

Quick Info Command (Edit Menu)
Send feedback

Provides the syntax for a variable, function, statement, method, or procedure selected in the Code window.

Quick Info shows the syntax for the item and highlights the current parameter. For functions and procedures with parameters, the parameter appears bold as you type it, until you type the comma used to delineate it from the next parameter.

To have Quick Info automatically appear as you type your code, select Auto Quick Info on the Editor tab in the Options dialog box.

Toolbar shortcut: . Keyboard shortcut: CTRL+I.


Quick Watch Command (Tools Menu)

 Copy code hover
[image]

Quick Watch Command (Tools Menu)
Send feedback

Displays the Quick Watch dialog box with the current value of the selected expression. Use this command to check the current value of a variable, property, or other expression for which you have not defined a watch expression. Select the expression from either the Code window or the Immediate window, and then choose the Quick Watch command. To add a watch expression based on the expression in the Quick Watch dialog box, choose the Add button.

Toolbar shortcut: . Keyboard shortcut: SHIFT+F9.


Quick Watch Dialog Box

 Copy code hover
[image]

Quick Watch Dialog Box
Send feedback

Displays the current value of a selected expression. This functionality is useful when debugging your code if you want to see the current value of a variable, property, or other expression.

Dialog Box Options

Current Context

Lists the names of the project, module, and procedure where the watch expression resides.

Expression

Shows the selected expression.

Value

Shows the value of the selected expression. The current value isn't displayed if the expression context isn't within a procedure listed in the Calls dialog box.

Add

Adds the expression to the Watch window.


Redo, Undo Commands (Edit Menu)

 Copy code hover
[image]

Redo, Undo Commands (Edit Menu)
Send feedback

Undo

Reverses the last editing action, such as typing text in the Code window or deleting controls. When you delete one or more controls, you can use the Undo command to restore the controls and all their properties.

Toolbar shortcut [image]. Keyboard shortcuts: CTRL+Z or ALT+BACKSPACE.

Note Note

You can't undo a Cut operation using the Undo command on a form.

Redo

Restores the last text editing or resizing and positioning of controls if no other actions have occurred since the last Undo.

Toolbar shortcut [image].

For text edits, you can use Undo and Redo to restore up to twenty edits.

These commands are unavailable at runtime, or if there was no previous edit, or if any other action has been performed after the last edit. Also, some large edits may cause low memory conditions that could prevent an Undo action.


References Command (Tools Menu)

 Copy code hover
[image]

References Command (Tools Menu)
Send feedback

Displays the References dialog box. This dialog box allows you to add an object library or type library reference to your project. This makes another application's objects available in your code. Once a reference is set, the referenced objects are displayed in the Object Browser.

You can also add references to other loaded and saved projects. If a project has not been saved, it appears as "UNSAVED: <ProjectName>" and you will be unable to make a reference to it.

Only available at design time.


References Dialog Box

 Copy code hover
[image]

References Dialog Box
Send feedback

Allows you to select another application's objects that you want available in your code by setting a reference to that application's object library.

Dialog Box Options

Available References

Lists the references available to your project.

  • After you set a reference to an object library by selecting the check box next to its name, you can find a specific object and its methods and properties in the Object Browser.

  • If you are not using any objects in a referenced library, you should clear the check box for that reference to minimize the number of object references Visual Basic must resolve, thus reducing the time it takes your project to compile. You can't remove a reference for an item that is used in your project.

  • If you remove a reference to an object that your are currently using in your project, you will receive an error the next time you refer to that object.

  • References not in use are listed alphabetically.

    Note Note

    You can't remove the "Visual Basic For Applications" and "Visual Basic objects and procedures" references, because they are necessary for running Visual Basic.

Priority Buttons

Moves references up, [image], and down, [image], on the list. When you refer to an object in code, Visual Basic searches each referenced library selected in the References dialog box in the order the libraries are displayed. If two referenced libraries contain objects with the same name, Visual Basic uses the definition provided by the library listed higher in the Available References box.

Result

Displays the name and path of the reference selected in the Available References box, as well as the language version.

Browse

Displays the Add Reference dialog box so that you can search other directories for and add references to the Available Resources box for the following types:

  • Type Libraries(*.olb, *.tlb, *.dll)

  • Executable Files (*.exe, *.dll)

  • ActiveX Controls (*.ocx)

  • All Files (*.*) The Add References dialog box is the Open common dialog box.


Remove

 Copy code hover
[image]

Remove <Item> Command (File Menu)
Send feedback

Permanently deletes the active form or module from the project. Not available when an item is not selected in the Project Explorer.

When removing a module from a project, make sure the remaining code doesn't refer to the removed item.

Before your item is deleted, you are asked if you want to export it as a file. If you click Yes in the message box, the Export File dialog box opens. If you click No, the item is deleted.

Important note Important

You cannot undo this action.


Rename Command (Shortcut Menu)

 Copy code hover
[image]

Rename Command (Shortcut Menu)
Send feedback

Displays the Rename dialog box so that you can change the name of the selected page in your Toolbox and create a tip.

Dialog Box Options

Caption

Allows you to give a new name to the tabbed page.

Control Tip Text

Allows you to create a tip for the tabbed page.


Rename Toolbar Dialog Box

 Copy code hover
[image]

Rename Toolbar Dialog Box
Send feedback

Allows you to rename your custom toolbars.

Dialog Box Option

Toolbar name

Type a new name for your toolbar.


Replace Command (Edit Menu)

 Copy code hover
[image]

Replace Command (Edit Menu)
Send feedback

Searches code in the project for the specified text and replaces it with the new text specified in the Replace dialog box.

Toolbar shortcut: . Keyboard shortcut: CTRL+H.

Dialog Box Options

Find What

Type or insert the information you want to find, or click the down arrow and select from the last four entries. If any text is selected or the cursor is on a word when you choose the command, this text is displayed in the Find What box.

Replace With

Type the text you want to use as the replacement text or paste it from the Clipboard. To delete the text in the Find What box from the document, leave the Replace With box empty.

Search

Specifies the search range.

  • Current Procedure — Searches only the current procedure.

  • Current Module — Searches only the current module.

  • Current Project — Searches all the modules in your project.

  • Selected Text — Searches a selected range of code in your project.

Direction

Sets the direction of the search to Down, Up, or All in the selected search range.

Find Whole Word Only

Searches for the full word by itself and not as part of a larger word.

Match Case

Finds all occurrences with the exact combination of uppercase and lowercase letters specified in the Find What box.

Use Pattern Matching

Searches using pattern-matching characters.

Find Next

Finds and selects the next occurrence of the text specified in the Find What box.

Cancel

Closes the dialog box without replacing text.

Replace

Confirms before replacing the search text with the replacement text.

Replace All

Replaces all occurrences of the search text with the replacement text without stopping for confirmation.


Reset

 Copy code hover
[image]

Reset <project> Command (Run Menu)
Send feedback

Clears the Call stack and clears the module level variables.

Toolbar shortcut: .


Run Menu

 Copy code hover
[image]

Run Menu
Send feedback

Run Sub/UserForm or Run Macro

Break

Reset

Design Mode/Exit Design Mode

Publish Mode


Run Project and Stop Project Commands (Run Menu)

 Copy code hover
[image]

Run Project and Stop Project Commands (Run Menu)
Send feedback

Run Project

Puts the project into a mode in which it can be used by other applications. This is used to debug and test the stand-alone project before building a dynamic-link library (DLL) (DLL) from it. The current project is registered, replacing any existing registration information for the project (the registry information for an existing DLL version of the project, for example).

Stop Project

Unregisters the project, and restores any previous registry information. This makes the in-memory project no longer able to be called from other applications.

Note Note

The Run Project and Stop Project commands are available only to the current stand-alone project. They are not available to host application document projects.
Note Note

This feature is not available in all versions of the Visual Basic Editor.


Run Sub/UserForm, Continue, and Run Macro Commands (Run Menu)

 Copy code hover
[image]

Run Sub/UserForm, Continue, and Run Macro Commands (Run Menu)
Send feedback

Run Sub/UserForm

Runs the current procedure if the cursor is in a procedure or runs the form if a form is currently active. This command becomes the Continue command when you are in break mode.

If neither Code window nor UserForm is active, this command becomes the Run Macro command.

Continue

Resumes running the current procedure or form.

Run Macro

Runs the macro.


Run to Cursor Command (Debug Menu)

 Copy code hover
[image]

Run to Cursor Command (Debug Menu)
Send feedback

When your application is in design mode, use Run To Cursor to select a statement further down in your code where you want execution to stop. Your application will run from the current statement to the selected statement and the current line of execution margin indicator, [image] appears in the Margin Indicator bar.

You can use this command, for example, to avoid stepping through large loops.

Keyboard shortcut: CTRL+F8.


Save

 Copy code hover
[image]

Save <host document> Command (File Menu)
Send feedback

Saves the current project and all of its components - forms and modules - with your document. A standalone project is saved separately as a project file with a .vba extension.

The Save command displays the Save As dialog box if this is the first time the project is being saved.

Toolbar shortcut: . Keyboard shortcut: CTRL+S.


Security Dialog Box

 Copy code hover
[image]

Security Dialog Box
Send feedback

Use this dialog box to determine the level of security used when opening documents, or to remove a certificate from the list of trusted sources.

Security Level Tab

The settings on this tab indicate the level of security used when opening documents or loading add-ins.

High

You can run code only in VBA projects that have been digitally signed and that are on your list of trusted sources (described below). If the certificate for a signed project is already on your list of trusted sources, it is automatically enabled and no warning is displayed. If the certificate for a signed project is not currently on your list of trusted sources, a warning is displayed and you can choose whether to enable or disable VBA code. If you choose to enable VBA code, you can choose to add the developer to the list of trusted sources. Before trusting a source, you should confirm that the source is responsible and uses a virus scanner before signing macros. Unsigned VBA projects are automatically disabled, and no warning is displayed. You cannot enable unsigned VBA projects at this security level.

Medium

A warning is displayed whenever a VBA project from a source that is not on your list of trusted sources is loaded. You can choose whether to enable or disable both digitally signed and unsigned VBA projects. If the project might contain a virus, you should choose to disable the add-in. If the project has been signed, you can choose to add the developer to the list of trusted sources. Before trusting a source, you should confirm that the source is responsible and uses a virus scanner before signing macros.

Low

If you are sure that all the VBA projects you load are safe, you can select this option — it turns off all virus protection. At this security level, VBA projects are always enabled.

Trusted Sources Tab

This tab lists the currently trusted certificates that can be used by developers to sign documents and add-ins. When you open a digitally signed document, the digital signature appears on your computer as a certificate. The certificate names the VBA project's source, plus additional information about the identity and integrity of that source. A digital signature does not necessarily guarantee the safety of a project, and you must decide whether you trust a project that has been digitally signed. If you know you can always trust macros from a particular source, you can add that macro developer to the list of trusted sources when you open the project.

Remove Button

If you added a certificate to your list of trusted sources when you first opened VBA project signed with that certificate, and later choose not to trust that source, you can use the Remove button to remove the certificate from your list of trusted sources. The next time a project signed with that certificate is opened, the virus protection behavior corresponding to the setting on the Security Level tab will occur.


Select All Command (Edit Menu)

 Copy code hover
[image]

Select All Command (Edit Menu)
Send feedback

Selects all of the code in the active Code window or all the controls on a form.


Select Certificate Dialog Box

 Copy code hover
[image]

Select Certificate Dialog Box
Send feedback

Allows you to select a certificate to assign to your project.

Dialog Box Options

Issued to

Displays the owner of a certificate.

Issued by

Displays the issuer of a certificate.

Intended Purposes

Displays the purpose of the certificate.

Friendly Name

Displays the certificate name that users will see when opening a signed document.

Expiration Date

Displays the date the certificate expires.

Location

Displays the certificate's path.

OK

Adds the selected certificate to the Digital Signature dialog box.

Cancel

Closes the dialog box without selecting any certificates.

View Certificate

Displays the certificate that users will see when opening a signed document.


Select Constant Command (Edit Menu)

 Copy code hover
[image]

Select Constant Command (Edit Menu)
Send feedback

Opens a dropdown list box in the Code window that contains the valid constants for a property that you typed, and that preceded the equal sign (=). The List Constants command also works for functions with arguments that are constants. To have the list box automatically open as you type your code, select Auto List Members on the Editor tab in the Options dialog box.

You can find the constant you want by:

  • Typing the name.

  • Using the up and down arrow keys to move up and down in the list.

  • Scrolling through the list and selecting the constant you want.

You can insert the constant into your code statement by:

  • Double-clicking the constant.

  • Selecting the constant and pressing TAB to insert the selection or pressing ENTER to insert the selection and move to the next line.

Toolbar shortcut: . Keyboard shortcut: CTRL+SHIFT+J.


Select Member Command (Edit Menu)

 Copy code hover
[image]

Select Member Command (Edit Menu)
Send feedback

Opens a dropdown list box in the Code window that contains the properties and methods available for the object The List Properties/Methods command also displays a list of the globally available methods when the pointer is on a blank space. To have the list box automatically open as you type your code, select Auto List Members on the Editor tab in the Options dialog box.

You can find the property or method you want in the list box by:

  • Typing the name. As you type, the property or method that matches the characters you type is selected and moves to the top of the list.

  • Using the up and down arrow keys to move up and down in the list.

  • Scrolling through the list and selecting the property or method you want.

You can insert the property or method into your statement by:

  • Double-clicking the property or method.

  • Selecting the property or method and pressing TAB to insert the selection or pressing ENTER to insert the selection and move to the next line.

    Note Note

    Objects of the type Variant do not show a list after the period (.).

Toolbar shortcut: . Keyboard shortcut: CTRL+J.


Set Next Statement Command (Debug Menu)

 Copy code hover
[image]

Set Next Statement Command (Debug Menu)
Send feedback

Sets the execution point to the line of code you choose. You can set a different line of code to execute after the currently selected statement by selecting the line of code you want to execute and choosing the Set Next Statement command or by dragging the Current Execution Line margin indicator to the line of code you want to execute.

Using Set Next Statement, you can choose a line of code located before or after the currently selected statement. When you run the code, any intervening code isn't executed. Use this command when you want to rerun a statement within the current procedure or to skip over statements you don't want to execute. You can't use Set Next Statement for statements in different procedures.

Toolbar shortcut: . Keyboard shortcut: CTRL+F9.


Show Hidden Members Command (Object Browser Shortcut Menu)

 Copy code hover
[image]

Show Hidden Members Command (Object Browser Shortcut Menu)
Send feedback

Shows and hides the hidden members in the Object Browser for each class. Hidden members are members that are not intended for use by the programmer of the reusable object and are not normally visible in the Object Browser. They appear as light gray text.


Show Next Statement Command (Debug Menu)

 Copy code hover
[image]

Show Next Statement Command (Debug Menu)
Send feedback

Highlights the next statement to be executed. Use the Show Next Statement command to place the cursor on the line that will execute next.

Available only in break mode.

Toolbar shortcut: .


Size Command (Shortcut Menu)

 Copy code hover
[image]

Size Command (Shortcut Menu)
Send feedback

Changes the pointer so that you can resize the active window or Toolbox.


Size to Fit Command (Format Menu)

 Copy code hover
[image]

Size to Fit Command (Format Menu)
Send feedback

Changes the height and width of an object to fit its contents.

Toolbar shortcut: .


Size to Grid Command (Format Menu)

 Copy code hover
[image]

Size to Grid Command (Format Menu)
Send feedback

Adjusts the height and width of the selected object to fit the nearest gridlines in the form. You can change the size of your grid on the General tab of the Options dialog box.

Toolbar shortcut: .


Standard Toolbar

 Copy code hover
[image]

Standard Toolbar
Send feedback

Contains buttons that are shortcuts to some commonly used menu items.

You can click a toolbar button once to carry out the action represented by that button. You can select the Show ToolTips option in the General tab of the Options dialog box if you want to display ToolTips for the toolbar buttons.

Toolbar Buttons

View <host application>

Toggles between the host application and the active Visual Basic document.

Insert

Opens a menu so that you can insert one of the following objects to your active project. The icon changes to the last object you added. The default is the form.

— UserForm

— Module

— Class Module

— Procedure

Save <host document name>

Saves the host document including the project and all of its components — forms and modules.

Cut

Removes the selected control or text and places it on the Clipboard.

Copy

Copies the selected control or text onto the Clipboard.

Paste

Inserts the contents of the Clipboard at the current location.

Find

Opens the Find dialog box and searches for the specified text in the Find What box.

Undo <last editing action>

Reverses the last editing action.

Redo <last editing action>

Restores the last text editing Undo actions if no other actions have occurred since the last Undo.

Run Sub/UserForm or Run Macro

Runs the current procedure if the cursor is in a procedure, runs the UserForm if a UserForm is currently active, or runs a macro if neither the Code window nor a UserForm is active.

Break

Stops execution of a program while it's running and switches to break mode.

Reset <project>

Clears the execution stack module level variables and resets the project.

Design Mode

Turns design mode off and on.

Project Explorer

Displays the Project Explorer, which displays a hierarchical list of the currently open projects and their contents.

Properties Window

Opens the Properties window so you can view the properties of the selected control.

Object Browser

Displays the Object Browser, which lists the object libraries, the type library, classes, methods, properties, events, and constants you can use in code, as well as the modules and procedures you defined for your project.

Toolbox

Displays or hides the Toolbox which contains all of the controls and insertable objects (such as a Microsoft Excel Chart) available to your application. This is only available when a UserForm is active.

Microsoft Visual Basic for Applications Help

Opens the help viewer for the associated application..


Step Into, Step Over, Step Out Commands (Debug Menu)

 Copy code hover
[image]

Step Into, Step Over, Step Out Commands (Debug Menu)
Send feedback

Step Into

Executes code one statement at a time.

When not in design mode, Step Into enters break mode at the current line of execution. If the statement is a call to a procedure, the next statement displayed is the first statement in the procedure.

At design time, this menu item begins execution and enters break mode before the first line of code is executed.

If there is no current execution point, the Step Into command may appear to do nothing until you do something that triggers code, for example click on a document.

Toolbar button: . Keyboard shortcut: F8.

Step Over

Similar to Step Into. The difference in use occurs when the current statement contains a call to a procedure.

Step Over executes the procedure as a unit, and then steps to the next statement in the current procedure. Therefore, the next statement displayed is the next statement in the current procedure regardless of whether the current statement is a call to another procedure. Available in break mode only.

Toolbar button: . Keyboard shortcut: SHIFT+F8.

Step Out

Executes the remaining lines of a function in which the current execution point lies. The next statement displayed is the statement following the procedure call. All of the code is executed between the current and the final execution points. Available in break mode only.

Toolbar button: . Keyboard shortcut: CTRL+SHIFT+F8.


Tab Order Command (View Menu)

 Copy code hover
[image]

Tab Order Command (View Menu)
Send feedback

Displays the Tab Order dialog box for the active Form.

Toolbar shortcut: .


Tab Order Dialog Box

 Copy code hover
[image]

Tab Order Dialog Box
Send feedback

Lists the tab order for the objects and allows you to change the order.

Dialog Box Options

Tab Order

Lists the objects, in their current order, on the form.

Move Up

Moves the selected object up one position in the tab order each time you click it.

Move Down

Moves the selected object down one position in the tab order each time you click it.


Toggle Breakpoint Command (Debug Menu)

 Copy code hover
[image]

Toggle Breakpoint Command (Debug Menu)
Send feedback

Sets or removes a breakpoint at the current line. You can't set a breakpoint on lines containing nonexecutable code such as comments, declaration statements, or blank lines.

A line of code in which a breakpoint is set appears in the colors specified in the Editor Format tab of the Options dialog box.

Toolbar shortcut: . Keyboard shortcut: F9.


Toggle Commands (Shortcut Menu)

 Copy code hover
[image]

Toggle Commands (Shortcut Menu)
Send feedback

Breakpoint

Sets or removes a breakpoint at the current line.

Bookmark

Displays or removes a bookmark at the active line in the Code window.


Toolbars Command (View Menu)

 Copy code hover
[image]

Toolbars Command (View Menu)
Send feedback

Lists the toolbars that are built into Visual Basic and the Customize command. You can:

  • Toggle the toolbars on and off.

  • Drag the toolbars to different locations on you desktop.

Debug

Displays the Debug toolbar which contains buttons for common debugging tasks.

Edit

Displays the Edit toolbar which contains buttons for common editing tasks.

Standard

Displays the Standard toolbar which is the default toolbar.

UserForm

Displays the UserForm toolbar which contains buttons specific to the form.

Customize

Displays the Customize dialog box where you can customize or create toolbars and your menu bar.


Toolbars Tab (Customize Dialog Box)

 Copy code hover
[image]

Toolbars Tab (Customize Dialog Box)
Send feedback

Allows you to create, rename, delete, and reset your toolbars,

Tab Options

Toolbars box

Displays the toolbars built into Visual Basic and any toolbars you create. When you show a toolbar, a check mark appears to the left of it.

Note Note

The Menu bar cannot be hidden. It can only be reset.

New

Opens the New Toolbar dialog box where you type the name for your new toolbar in the Toolbar Name box.

Rename

Opens the Rename Toolbar dialog box where you type the new name for your toolbar. Only available if you select a user-defined toolbar.

Delete

Deletes a user-defined toolbar from your project. Only available if you select a user-defined toolbar.

Reset

Removes any changes to the built-in toolbars and resets them to their original state. Only available if you select a built-in toolbar.


Toolbox

 Copy code hover
[image]

Toolbox
Send feedback

Displays the standard Visual Basic controls plus any ActiveX controls and insertable objects you have added to your project.

  • You can customize the Toolbox by adding pages to it or by adding controls using the Additional Controls command from the Tools menu. When you add a page, a Select Objects tool is always available on the page.

Standard Toolbox Controls

Select Objects

Select Objects is the only item in the Toolbox that doesn't draw a control. When you select it, you can only resize or move a control that has already been drawn on a form.

Label

Allows you to have text that you do not want the user to change, such as a caption under a graphic.

TextBox

Holds text that the user can either enter or change.

ComboBox

Allows you 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.

ListBox

Use to display a list of items from which the user can choose. The list can be scrolled if it has more items than can be displayed at one time.

CheckBox

Creates a box that the user can easily choose to indicate if something is true or false, or to display multiple choices when the user can choose more than one.

OptionButton

Allows you to display multiple choices from which the user can choose only one.

ToggleButton

Creates a button that toggles on and off.

Frame

Allows you to create a graphical or functional grouping for controls. To group controls, draw the frame first, and then draw controls inside the frame.

CommandButton

Creates a button the user can choose to carry out a command.

TabStrip

Allows you to define multiple pages for the same area of a window or dialog box in your application.

MultiPage

Presents multiple screens of information as a single set.

ScrollBar

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

SpinButton

A spinner control you can use with another control to increment and decrement numbers. You can also use it to scroll back and forth through a range of values or a list of items.

Image

Displays a graphical image from a bitmap, icon, or metafile on your form. Images displayed in an Image control can only be decorative and use fewer resources than a PictureBox.


Toolbox Command (View Menu)

 Copy code hover
[image]

Toolbox Command (View Menu)
Send feedback

Displays or hides the Toolbox, which contains the controls currently available to your application.

Toolbar shortcut: .


Tools Menu

 Copy code hover
[image]

Tools Menu
Send feedback

References

Macros

Options

<Project> Properties

Digital Signature


UserForm Command (Insert Menu)

 Copy code hover
[image]

UserForm Command (Insert Menu)
Send feedback

Creates a new form and adds it to your project.


UserForm Command Bar

 Copy code hover
[image]

UserForm Command Bar
Send feedback

Contains buttons that are shortcuts to some commonly used menu items that are useful for working with forms.

You can click a toolbar button once to carry out the action represented by that button. You can select the Show ToolTips option in the General tab of the Options dialog box if you want to display ToolTips for the toolbar buttons.

Toolbar Buttons

Bring To Front

Moves the selected objects to the front of all other objects on a form.

Send To Back

Moves the selected objects behind all other objects on a form.

Group

Creates a group of the selected objects.

Ungroup

Ungroups the objects that were previously grouped.

Align

  • Lefts — Aligns the horizontal position of the selected objects, putting the left-most edges in line.

  • Centers — Aligns the horizontal position of the selected objects, putting the centers in line.

  • Rights — Aligns the horizontal position of the selected objects, putting the right-most edges in line.

  • Tops — Aligns the vertical position of the selected objects, putting the tops in line.

  • Middles — Aligns the vertical position of selected objects, putting the middles in line.

  • Bottoms — Aligns the vertical position of the selected objects, putting the bottoms in line.

  • to Grid — Aligns the top left of the selected object to the closest grid. The object is not resized.

Center

  • Horizontally — Centers the selected objects horizontally.

  • Vertically — Centers the selected objects vertically.

Make Same Size

  • Width — Adjusts width.

  • Height — Adjusts height.

  • Both — Adjusts both the width and the height.

Zoom

Reduces or enlarges the display of all controls on the UserForm. You can set any magnification between 10 and 400 percent.


UserForm Windowc (Visual Basic User Interface)

 Copy code hover
[image]

UserForm Windowc (Visual Basic User Interface)
Send feedback

Allows you to create the windows or dialog boxes in your project. You draw and view controls on a form.

While you are designing a form:

  • Each form window has a Maximize, Minimize, and Close button.

  • You can view the form grid and determine the size of the gridlines from the General tab of the Options dialog box.

  • Use the buttons in the Toolbox to draw controls on the form. You can set your controls to align with the grid of your form from the General tab of the Options dialog box.


UserForm Window Keys

 Copy code hover
[image]

UserForm Window Keys
Send feedback

Use these key combinations in the UserForm window:

Press | To
SHIFT+CTRL +ALPHA | Select a property in the Property list of the Properties window.
ALPHA | Enter a value in the Properties window for the selected property.
F7 | Open the Code window for the selected object.
DEL or DELETE | Delete the selected controls without placing them on the Clipboard.
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.
SHIFT+CLICK | Select multiple controls.
CTRL+CLICK+DRAG | Add or remove controls from the current selection.
F6 | Display the Properties window (design time only).
SHIFT+F10 | View shortcut.
CTRL+J | Bring to front (affects overlapping controls at design time only).
CTRL+K | Send to back (affects overlapping controls at design time only).

To deselect all controls, click the form. To select controls in a container, first deselect the container and then CTRL+CLICK+DRAGaround the desired controls.


Vertical Spacing Commands (Format Menu)

 Copy code hover
[image]

Vertical Spacing Commands (Format Menu)
Send feedback

Changes the vertical space between the selected objects, based on the object with focus. When an object has focus, white handles appear on its borders.

Make Equal

Moves the selected objects so that there is equal space between them using the top and bottom objects as the endpoints.

Toolbar shortcut: .

Increase

Increases the vertical spacing by one grid based on the object with focus. You can change the size of your grid units in the General tab of the Options dialog box.

Toolbar shortcut: .

Decrease

Decreases the vertical spacing by one grid based on the object with focus. You can change the size of your grid units in the General tab of the Options dialog box.

Toolbar shortcut: .

Remove

Removes the vertical spacing so that the object's borders are touching, based on the object with focus

Toolbar shortcut: .

Note Note

The object with focus does not move but the other objects move around it.
Note Note

If using the Vertical Spacing command does not produce the results you want, try to manually rearrange some of the objects and repeat the command. Also, try the using the Horizontal Spacing command.


View Definition Command (Object Browser Shortcut Menu)

 Copy code hover
[image]

View Definition Command (Object Browser Shortcut Menu)
Send feedback

Takes you to the definition of the selected member.


View Menu

 Copy code hover
[image]

View Menu
Send feedback

Code

Object

Definition

Last Position

Object Browser

Immediate Window

Locals Window

Watch Window

Call Stack

Project Explorer

Properties Window

Toolbox

Tab Order

Toolbars

<Host application>


View Object and View Code Commands (Shortcut Menu)

 Copy code hover
[image]

View Object and View Code Commands (Shortcut Menu)
Send feedback

Allows you to view either the Design window or the Code window.

View Object

Displays or activates the selected item.

View Code

Displays or activates the Code window for a currently selected object.


Visual Basic Menus

 Copy code hover
[image]

Visual Basic Menus
Send feedback

Visual Basic has two types of menus, built-in and shortcut.

Built-in Menus

Built-in menus appear on the menu bar across the top of the Visual Basic window. Each menu contains commands that relate to the menu name. For example, the Format menu contains commands used for formatting your form. Some of the commands have submenus that contains more specific commands. For example, the Toolbars command on the View menu has a submenu that contains the names of the toolbars and the Customize command. You can use the Customize command to modify the built-in menus or to add commands to the menu bar.

Shortcut Menus

Shortcut menus are menus containing frequently used commands that appear when you click the right mouse button or press SHIFT+F10.

Note Note

To find information on a command on a menu, use the Search Reference Index command on the Help menu and search for the name of the command.


Watch Window

 Copy code hover
[image]

Watch Window
Send feedback

Appears automatically when watch expressions are defined in the project.

You can:

  • Change the size of the column headers by dragging its border to the right to make it larger or to the left to make it smaller.

  • Drag a selected variable to the Immediate window or the Watch window.

  • Close the window by clicking the Close box. If the Close box is not visible, double-click the Title bar to make the Close box visible, then click it.

Window Elements

Expression

Lists the watch expression with the Watch icon, [image] on the left.

Value

List the value of the expression at the time of the transition to break mode.

You can edit a value and then press ENTER, the UP ARROW key, the DOWN ARROW key, TAB, SHIFT+TAB, or click somewhere on the screen to validate the change. If the value is illegal, the Edit field remains active and the value is highlighted. A message box describing the error also appears. Cancel a change by pressing ESC.

Type

Lists the expression type.

Context

Lists the context of the watch expression.

If the context of the expression isn't in scope when going to break mode, the current value isn't displayed.

You can close the window by clicking the Close box. If the Close box is not visible, double-click the Title bar to make the Close box visible, then click it.


Watch Window Command (View Menu)

 Copy code hover
[image]

Watch Window Command (View Menu)
Send feedback

Displays the Watch window and displays the current watch expressions. The Watch window appears automatically if watch expressions are defined in the project.

If the context of the expression isn't in scope when going to break mode, the current value isn't displayed.

Toolbar shortcut: .


Watch Window Keyboard Shortcuts

 Copy code hover
[image]

Watch Window Keyboard Shortcuts
Send feedback

Use these key combinations in the Watch window:

Press | To
SHIFT+ENTER | Display the selected watch expression.
CTRL+W | Display Edit Watch dialog box.
ENTER | Expands or collapses the selected watch value if it has a plus (+) or minus (-) to the left of it.
F2 | Display the Object Browser.
SHIFT+F10 | View shortcut menu.


Wildcard Characters used in String Comparisons

 Copy code hover
[image]

Wildcard Characters used in String Comparisons
Send feedback

Built-in pattern matching provides a versatile tool for making string comparisons. The following table shows the wildcard characters you can use with the Like operator and the number of digits or strings they match.

Character(s) in pattern | Matches in expression
? | Any single character
* | Zero or more characters
# | Any single digit (09)
[charlist] | Any single character in charlist
[!charlist] | Any single character not in charlist

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in expression and can include almost any characters in the ANSI character set, including digits. In fact, the special characters opening bracket ([ ), question mark (?), number sign (#), and asterisk (*) can be used to match themselves directly only if enclosed in brackets. The closing bracket ( ]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

In addition to a simple list of characters enclosed in brackets, charlist can specify a range of characters by using a hyphen (-) to separate the upper and lower bounds of the range. For example, using [A-Z] in pattern results in a match if the corresponding character position in expression contains any of the uppercase letters in the range A through Z. Multiple ranges can be included within the brackets without any delimiting. For example, [a-zA-Z0-9] matches any alphanumeric character.

Other important rules for pattern matching include the following:

  • An exclamation mark (!) at the beginning of charlist means that a match is made if any character except those in charlist are found in expression. When used outside brackets, the exclamation mark matches itself.

  • The hyphen (-) can be used either at the beginning (after an exclamation mark if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of ANSI characters.

  • When a range of characters is specified, they must appear in ascending sort order (A-Z or 0-100). [A-Z] is a valid pattern, but [Z-A] isn't.

  • The character sequence [ ] is ignored; it's considered to be a zero-length string ("").


Window Menu Commands

 Copy code hover
[image]

Window Menu Commands
Send feedback

Split

Toggles splitting the Code window in half horizontally. Only available when the Code window is active.

Toolbar shortcut: .

Tile Horizontally

Tiles all open document windows in your project horizontally.

Toolbar shortcut: .

Tile Vertically

Tiles all open document windows in your project vertically.

Toolbar shortcut: .

Cascade

Rearranges all open document windows in your project so they overlap in a cascade.

Toolbar shortcut: .

Arrange Icons

Arranges the icons of any document windows you have minimized, neatly at the bottom left of the window.

Window List

Lists all open document windows.


Zoom Command

 Copy code hover
[image]

Zoom Command
Send feedback

Reduces or enlarges the display of the selected form. You can choose or type a magnification between 10 and 400 percent.

Only available on theUserForm toolbar.

Toolbar:


Add Watch Command (Debug Menu)

 Copy code hover
[image]

Add Watch Command (Debug Menu)
Send feedback

Published: July 16, 2012

Displays the Add Watch dialog box in which you enter a watch expression. The expression can be any valid Basic expression. Watch expressions are updated in the Watch window each time you enter break mode.

Toolbar shortcut: .


Add Watch Dialog Box

 Copy code hover
[image]

Add Watch Dialog Box
Send feedback

Use to enter a watch expression. The expression can be a variable, a property, a function call, or any other valid Basic expression. Watch expressions are updated in the Watch window each time you enter break mode or after execution of each statement in the Immediate window.

You can drag selected expressions from the Code window into the Watch window.

Important note Important

When selecting a context for a watch expression, use the narrowest scope that fits your needs. Selecting all procedures or all modules could slow down execution considerably, since the expression is evaluated after execution of each statement. Selecting a specific procedure for a context affects execution only while the procedure is in the list of active procedure calls, which you can see by choosing the Call Stack command on the View menu.

Dialog Box Options

Expression

Displays the selected expression by default. The expression is a variable, a property, a function call, or any other valid expression. You may enter a different expression to evaluate.

Context

Sets the scope of the variables watched in the expression.

  • Procedure — Displays the procedure name where the selected term resides (default). Defines the procedure(s) in which the expression is evaluated. You may select all procedures or a specific procedure context in which to evaluate the variable.

  • Module — Displays the module name where the selected term resides (default). You may select all modules or a specific module context in which to evaluate the variable.

  • Project — Displays the name of the current project. Expressions can't be evaluated in a context outside of the current project.

Watch Type

Determines how Visual Basic responds to the watch expression.

  • Watch Expression — Displays the watch expression and its value in the Watch window. When you enter break mode, the value of the watch expression is automatically updated.

  • Break When Value Is True — Execution automatically enters break mode when the expression evaluates to true or is any nonzero value (not valid for string expressions).

  • Break When Value Changes — Execution automatically enters break mode when the value of expression changes within the specified context.


Debug Toolbar

 Copy code hover
[image]

Debug Toolbar
Send feedback

Contains buttons that are shortcuts to some commonly used menu items frequently used in debugging code.

You can click a toolbar button once to carry out the action represented by that button. You can select the Show ToolTips option in the General tab of the Options dialog box if you want to display ToolTips for the toolbar buttons.

Toolbar Buttons

Design Mode

Turns design mode off and on.

Run Sub/UserForm or Run Macro

Runs the current procedure if the cursor is in a procedure, runs the UserForm if a UserForm is currently active, or runs a macro if neither the Code window nor a UserForm is active.

Break

Stops execution of a program while it is running and switches to break mode.

Reset

Clears the execution stack and module level variables and resets the project.

Toggle Breakpoint

Sets or removes a breakpoint at the current line.

Step Into

Executes code one statement at a time.

Step Over

Executes code one procedure or statement at a time in the Code window.

Step Out

Executes the remaining lines of a procedure in which the current execution point lies.

Locals Window

Displays the Locals window.

Immediate Window

Displays the Immediate window.

Watch Window

Displays the Watch window.

Quick Watch

Displays the Quick Watch dialog box with the current value of the selected expression.

Call Stack

Displays the Calls dialog box, which lists the currently active procedure calls (procedures in the application that have started but are not completed).


Icons Used in the Object Browser and Code Windows

 Copy code hover
[image]

Icons Used in the Object Browser and Code Windows
Send feedback

The Object Browser and Code window contain many icons that represent classes and members. The following is a list of icons and what they represent.

This Icon: | Represents a:
 | Property
 | Default Property
 | Method
 | Default Method
 | Event
 | Constant
 | Module
 | Class
 | User Defined Type
 | Global
 | Library
 | Project
 | Built-in keywords and types
 | Enum


Project Explorer Command (View Menu)

 Copy code hover
[image]

Project Explorer Command (View Menu)
Send feedback

Displays the Project Explorer, which displays a hierarchical list of the currently open projects and their contents.

The Project Explorer is a navigational and management tool only. You cannot build an application from the Project Explorer.

Toolbar shortcut: . Keyboard shortcut: CTRL+R.


Project Explorer Keyboard Shortcuts

 Copy code hover
[image]

Project Explorer Keyboard Shortcuts
Send feedback

Use these key combinations in the Project Explorer:

Press | To
ENTER | Open the selected file from the list, or expand and collapse the list to show its subentries.
SHIFT+ENTER | Open the Code window for the selected file.
F7 | Open the Code window for the selected file.
SHIFT+F10 | View shortcut menu.
HOME | Select the first file in the list.
END | Select the last file in the list.
RIGHT ARROW | Expands a list and then selects a subentry in the list each time you press it.
LEFT ARROW | Selects a subentry in the list and then moves up the list each time you press it until the subentry list collapses into a folder.
UP ARROW | Moves up the list one entry at a time.
DOWN ARROW | Moves down the list one entry at a time.


Office 2013 documentation copyright notice

 Copy code hover
[image]

Office 2013 documentation copyright notice
Send feedback

Published: July 16, 2012

This document is provided "as-is". Information and views expressed in this document, including URL and other Internet Web site references, may change without notice. You bear the risk of using it.

Some examples depicted herein are provided for illustration only and are fictitious. No real association or connection is intended or should be inferred.

This document does not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes.

© 2013 Microsoft Corporation. All rights reserved.

Microsoft, Access, ActiveX, ClearType, Excel, FrontPage, InfoPath, IntelliSense, JScript, MSDN, MS-DOS, MSN, OneNote, Outlook, PowerPoint, SharePoint, Silverlight, SmartArt, SQL Server, Visio, Visual Basic, Visual C#, Visual C++, Visual Studio, Win32, Windows, Windows PowerShell, Windows Server, and Windows Vista are trademarks of the Microsoft group of companies.

All other trademarks are property of their respective owners.