Forum Discussion
Hello,
The key is to use the Sys.WaitProcess method to wait for the application to appear, then use a script to open a new document or confirm one is open before trying to get the OLE object.
Launch the Application and Wait: Start the Office application (Word or Excel) from your TestComplete script as you normally would. Use Sys.WaitProcess to ensure the process is running and accessible.
Ensure a Document is Open: This is the most crucial step. Use your script to activate the application and either open a new document or verify that an existing document is open. This action forces the application to register itself in the ROT.
Get the OLE Object: Once you've confirmed a document is open, you can proceed to get the OLE object and access its properties and methods.
procedure GetOfficeOLEObject;
var
wordApp: OleVariant;
wordProcess: OleVariant;
docCount: Integer;
begin
// Step 1: Launch Word and wait for the process to be available
wordProcess := Sys.WaitProcess('WINWORD');
// Activate the Word application window to ensure it registers in the ROT
wordProcess.Window('#0', '', 1).Activate;
// Wait a moment for the activation to take effect
aqUtils.Delay(2000);
// Step 2: Ensure a document is open. If no documents are open, create a new one.
wordApp := Sys.OleObject('Word.Application');
// Check the number of open documents. The Documents property is the key.
docCount := wordApp.Documents.Count;
// If no document is open, create a new one to enable OLE functionality.
if docCount = 0 then
begin
Log.Message('No Word document is open. Creating a new one.');
wordApp.Documents.Add;
// It's good practice to wait for the new document to be fully ready
aqUtils.Delay(1000);
end;
// Step 3: Now you can safely access properties and methods
Log.Message('Word version is: ' + wordApp.Version);
Log.Message('Active document name is: ' + wordApp.ActiveDocument.Name);
// Example of a task: writing text to the active document
wordApp.Selection.TypeText('Hello from TestComplete!');
// Clean up by closing the application (or save/close the document first if needed)
wordApp.Quit;
Log.Message('Word application has been closed.');
end;
The old "activate another window" workaround often failed because it didn't guarantee that a document was open within the Office application. The core issue, as highlighted in the Microsoft support article you cited, is that the Office application's OLE automation server (the part that provides properties and methods) is often only fully functional when a document is present. Without an open document, many commands like Application.ActiveDocument will fail.