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

前端 未结 2 796
你的背包
你的背包 2020-12-11 05:33

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

Current code,

Private Declare Function SetForegroundWindow         


        
相关标签:
2条回答
  • 2020-12-11 06:12

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

    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 exact string.


    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 PtrSafe keyword and the LongPtr data type:

    #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
    
    0 讨论(0)
  • 2020-12-11 06:23

    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
    
    0 讨论(0)
提交回复
热议问题