1
votes

I have a VB.NET application that uses Microsoft.Office.Interop.Excel to simply open up a spreadsheet, pump over some data to it, refresh the data in the pivot tables and then present the user with the spreadsheet.

The code is pretty simple (error handling not shown):

    ' Start Excel Application
    xlApp = New Excel.ApplicationClass

    ' Get Excel Workbooks 
    xlWorkBooks = xlApp.Workbooks

    ' Open workbook 
    xlWorkBook = xlWorkBooks.Open(Filename:=sExcelDocFullPath, IgnoreReadOnlyRecommended:=blnIgnoreReadOnly)

    If Not xlWorkBook Is Nothing Then

        ' Pump some data over (code not shown)
        ' Make the first worksheet in the document active
        CType(xlWorkBook.Worksheets(1), Excel.Worksheet).Activate()

        'Return control of Excel to the user
        xlApp.Visible = True
        xlApp.UserControl = True

        ' Refresh workbooks (with alerts off, so as not to hassle user )
        xlApp.DisplayAlerts = False
        xlWorkBook.RefreshAll()
    End If

What happens when this code is run, is that Excel is opened up behind the calling app and because we are refreshing the data connections, the small Excel "SQL Server Login" dialog is also displayed behind the calling app and thus the user needs to ALT+TAB to Excel or click on Excel in the Task Bar - neither is a great experience for the user. We'd like the Login dialog to appear infront of the calling app.

Can anyone suggest how this could be achieved ? I've tried moving the setting of the Visible & UserControl properties to after the RefreshAll, but that doesn't make any difference.

Cheers,

Chris.

1
We have similar problems and have tried different approaches. First, you can set windowState property to XlMaximized (or XlNormal). For other options, you need the window handle and, when having it, telling it to be onTop. But finding the handle is not easy... There is a property in the Excel application, hwnd. Also, you could get windows form the workbookCarlos E. Ferro

1 Answers

2
votes

Sorry for C#, I don't know VB, so I cannot translate myself, but the main idea is to use WinAPI:

[DllImport("user32.dll", SetLastError = true)]
public static extern bool BringWindowToTop(IntPtr hWnd);

You can get hwnd from xlApp:

BringWindowToTop((INtPtr)XlApp.Hwnd);