VBA API 声明。无论应用程序如何,都将窗口放在前面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34481674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:08:08  来源:igfitidea点击:

VBA API declarations. Bring window to front , regardless of application

excelvba

提问by Sam

I am trying to bring and Excel window to the front of all applications running regardless.

我试图将 Excel 窗口放在所有正在运行的应用程序的前面。

Current code,

当前代码,

Private Declare Function SetForegroundWindow _
                     Lib "user32" _
                   (ByVal hWnd As Long) As Long

Public Sub Bring_to_front()   
    SetForegroundWindow wb.Application.hWnd    
End Sub
Sub Test()    
     Set wb = Workbooks("MyWorkBook.xlxs")
      call Bring_to_front
End Sub

At the moment nothing happens.

目前什么都没有发生。

采纳答案by Sam

Found the answer to what I as trying to do after a bit more research.

经过更多的研究,找到了我想要做的事情的答案。

This will bring the worksheet you specify to the front.

这会将您指定的工作表带到前面。

Public Declare Function SetForegroundWindow _
Lib "user32" (ByVal hwnd As Long) As Long

Public Sub Bring_to_front()
    Dim setFocus As Long

    ThisWorkbook.Worksheets("Sheet1").Activate
    setfocus = SetForegroundWindow(Application.hwnd)
End Sub

回答by Sam

You don't need an API for this, you can use something like:

您不需要为此提供 API,您可以使用以下内容:

Sub BringXLToFront()
    AppActivate Application.Caption
End Sub

The AppActivate()method in VBA takes a string argument, and it will activate (i.e. bring it to the front)any window that contains that exactstring.

AppActivate()在VBA方法需要一个字符串参数,并且将激活(即,它带至前),其中包含的任何窗口确切字符串。



More specific to your question though - you need to understand how APIs work in VBA a bit more - if you're using a x64 system then you need to use conditional compilation and declare the API function as pointer-safe by using the PtrSafekeyword and the LongPtrdata type:

更具体到您的问题 - 您需要更多地了解 API 如何在 VBA 中工作 - 如果您使用的是 x64 系统,那么您需要使用条件编译并通过使用PtrSafe关键字和LongPtr数据类型:

#If Win64 Then
    Private Declare PtrSafe Function SetForegroundWindow Lib "user32" _
               (ByVal hWnd As LongPtr) As LongPtr
#Else
    Private Declare Function SetForegroundWindow Lib "user32" _
               (ByVal hWnd As Long) As Long
#End If