简体   繁体   中英

Bringing an Excel window to foreground from Access

I am trying to open an Excel file from Access and it does work, however the Excel window pops up in the background (behind the Access window), which is not very user friendly. Here is the code I use:

Private Function OpenExcelAttachment()
Dim MyXL As Object
Set MyXL = CreateObject("Excel.Application")
With MyXL

   Dim FullPath As String, Name As String
   Name = "\ExcelFile.xlsx"
   FullPath = CurrentProject.Path & Name
   .Workbooks.Open FullPath
   .Visible = True

 End With

How can I make the Excel window appear in the foreground (on top of all opened windows) instead?

Thank you!

I would first check for already open instance of Excel. If you must allow for multiple instances of the Application, then it will be trickier. If you are OK with only using one instance of Excel, then I think this should work using the AppActivate statement.

Private Function OpenExcelAttachment()
Dim MyXL As Object

On Error Resume Next
Set MyXL = GetObject(,"Excel.Application")
If Err.Number <> 0 Then Set MyXL = CreateObject("Excel.Application")
On Error GoTo 0

With MyXL
   Dim FullPath As String, Name As String
   Name = "\ExcelFile.xlsx"
   FullPath = CurrentProject.Path & Name
   .Workbooks.Open FullPath
   .Visible = True
End With

AppActivate "Microsoft Excel"

End Function

You have to call AllowSetForegroundWindow before making Excel visible. I don't develop in VBA, but I think it would look like this:

Private Declare Function AllowSetForegroundWindow Lib "user32.dll" (ByVal dwProcessId As Long) As Long
Private Function OpenExcelAttachment()
Dim MyXL As Object
Set MyXL = CreateObject("Excel.Application")
AllowSetForegroundWindow -1
With MyXL

   Dim FullPath As String, Name As String
   Name = "\ExcelFile.xlsx"
   FullPath = CurrentProject.Path & Name
   .Workbooks.Open FullPath
   .Visible = True

A little late to the party here,

(using Office 2013)

If Excel isn't already open, I find that:

.invisible = true

Brings the Excel window to the front if Excel isn't open. If Excel is already open however, I find I need to set invisible to false first then reset to true to get the window to the front

.invisible = false
.invisible = true

Maybe this should work?

Private Function OpenExcelAttachment()
Dim MyXL As Object
Set MyXL = CreateObject("Excel.Application")
With MyXL

   Dim FullPath As String, Name As String
   Name = "\ExcelFile.xlsx"
   FullPath = CurrentProject.Path & Name
   .Workbooks.Open FullPath

   .Visible = False
   .Visible = True

 End With

EDIT:

Actually, what seems to work far better is AppActivate

AppActivate(nameOfExcelFile)

AppActivate Statement

AppActivate oWrkBk.Name & "-Excel"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM