Example: The Window Object
Another object that's common to almost all applications is the Window object, which represents an open window in an application. Note that this isn't the same as an open document. Rather, the Window object is just a container for a document, so the associated properties and methods have no effect on the document data. You can use VBA to change the window state (maximized or minimized), size and move windows, navigate open windows, and much more. In the next three sections you learn how to specify a Window object in your code, how to open a new window, and how to activate a window.
Specifying a Window Object
If you need to perform some action on a window or change a window's properties, you need to tell the application which window you want to use. VBA gives you two ways to do this:
- Use the Windows object-The Windows object is the collection of all the open windows
in the application. To specify a window, either use its index number (as given by the
numbers beside the windows on the application's Windows menu) or enclose the window
caption (in other words, the text that appears in the window's title bar) in quotation
marks. For example, if the Budget.doc window is listed first in the Window menu,
the following two statements would be equivalent:
Windows(1) Windows("Budget.doc")
- Use the ActiveWindow object-The ActiveWindow object represents the window that
currently has the focus. For example, the following statement uses the WindowState
property (common to all Window objects) to maximize the active Word window:
ActiveWindow.WindowState = wdWindowStateMaximize
Opening a New Window
If you need to create a new window, use the Window object's NewWindow method:
Window.NewWindow
Window
The Window object from which you want to create the new window.
Note that this argument is optional in some applications. In Word, for example, if you omit Window, the active window is used.
Activating a Window
If your code needs to switch from one window to another, you need to activate the other window. You do that by running the Window object's Activate method, which activates the specified open window. For example, the following statement activates the Finances.xls window:
Windows("Finances.xls").Activate