Working with Microsoft Excel

Initializing a New Microsoft Excel COM Object

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

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

An instance of the COM object is created in the computer memory. To use full features in Excel, create a new book or open an existing one, and set the Application.Visible (See the Visual Basic help)  to the True value:

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

After this, the application window is displayed on the screen.

Displaying Application Window in Foreground in Windows 7

In Windows 7, Microsoft developers changed the way of working with windows. Thus, the code specified above results in creating an Excel application but the application does not get focus. The application window is placed in the background and the application shortcut becomes available on the taskbar only. To place the window in the foreground and get the focus, before displaying the window, minimize the window size and restore the size. To do this in Fore, use the following code:

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 from Fore