Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...