从Access中将Excel窗口置于前台

时间:2014-08-17 20:45:19

标签: excel vba ms-access

我正在尝试从Access打开一个Excel文件,它确实有效,但是Excel窗口会在后台弹出(在Access窗口后面),这对用户不太友好。这是我使用的代码:

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

如何让Excel窗口出现在前台(在所有打开的窗口之上)?

谢谢!

3 个答案:

答案 0 :(得分:2)

我首先检查已经打开的Excel实例。如果您必须允许应用程序的多个实例,那么它将更加棘手。如果您只使用一个Excel实例,那么我认为这应该可以使用AppActivate语句。

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

答案 1 :(得分:0)

在让Excel可见之前,您必须致电AllowSetForegroundWindow。我没有在VBA中开发,但我认为它看起来像这样:

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

答案 2 :(得分:0)

这里的派对有点晚了,

(使用Office 2013)

如果Excel尚未打开,我会发现:

.invisible = true

如果Excel未打开,则将Excel窗口置于前面。如果Excel已经打开,我发现我需要首先将invisible设置为false然后重置为true以使窗口显示在前面

.invisible = false
.invisible = true

也许这应该有效?

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

编辑:

实际上,似乎工作得更好的是AppActivate

AppActivate(nameOfExcelFile)

AppActivate Statement