Working with Microsoft Excel

Initializing New Microsoft Excel COM-Object

To create a Microsoft Excel COM object, specify the Excel.Application program identifier using the Variant.CreateObject method:

Var
    Excel: Variant;
Begin
    Excel := Variant.CreateObject("Excel.Application");

The COM-object instance will be created in the computer memory. For full-function work with Excel application, it is required to create a new book or open the existing one, then set the Application.Visible property (see Visual Basic help) to True:

Var
    Excel: Variant;
Begin
    Excel := Variant.CreateObject("Excel.Application");
    //Create a new book
    Excel.GetProperty("Workbooks").Invoke("Add"New Variant[0]);
    //or open existing book
    Excel.GetProperty("Workbooks").Invoke("Open""c:\Book1.xlsx");
    //Display application
    Excel.SetProperty("Visible"True);

After that, the application window will be displayed on the screen.

Displaying Application Window To the Forefront in Windows 7

The Microsoft developers changed the approach to work with windows in the Windows 7 operating system, that is why the specified above code will create the Excel application but the application will not get the focus. The application window will be in the background, the shortcut will be available only on the taskbar. To bring the window to the front and get is focused, minimize the window size before its displaying and then restore the size. The following code can be used in Fore for it:

Enum XlWindowState
    xlMaximized = -4137, xlMinimized = -4140, xlNormal = -4143
End Enum XlWindowState;

Var
    Excel: Variant;
Begin
    Excel := Variant.CreateObject("Excel.Application");
    Excel.GetProperty("Workbooks").Invoke("Add"New Variant[0]);
    Excel.SetProperty("WindowState", XlWindowState.xlMinimized);
    Excel.SetProperty("WindowState", XlWindowState.xlMaximized);
    Excel.SetProperty("Visible"True);

See also:

Working with COM-objects