Bring Excel window to front from Access
I'm trying to open an Excel file from Access, but it works, however the Excel window appears in the background (behind the Access window), which is not very convenient. Here is the code I'm using:
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 open windows)?
Thank!
source to share
First I have to check an already open instance of Excel. If you have to allow multiple instances of the application, then this is more difficult. If you are fine using just one instance of Excel, I think this should work with 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
source to share
You must call AllowSetForegroundWindow
before you can make Excel visible. I am not developing 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
source to share
It's a little late to the party here,
(using Office 2013)
If Excel is not open yet, I found that:
.invisible = true
Brings an Excel window forward if Excel is not open. If Excel is already open, I found that I need to set the invisible value to false first and 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:
In fact, AppActivate seems to work much better
AppActivate(nameOfExcelFile)
source to share