Name

Application.Hwnd

Synopsis

Returns a handle to the top-level Excel window. You use handles with the Windows API to do low-level tasks not available through Excel objects. For example, the following code displays the Excel always on top of all other windows, even if Excel doesn’t have focus:

Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, _
  ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, _
  ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
Const SWP_NOSIZE = &H1
Const SWP_NOMOVE = &H2
Const HWND_TOPMOST = -1
Const HWND_NOTOPMOST = -2
 
Sub TestShowXLOnTop(  )
    ' Change to False to return to normal.
    ShowXLOnTop True
End Sub
 
Public Function ShowXLOnTop(ontop As Boolean)
    Dim hXl As Long, setting As Long
    If ontop Then setting = HWND_TOPMOST _
      Else setting = HWND_NOTOPMOST
    hXl = Application.hwnd
    SetWindowPos hXl, setting, 0, 0, _
      0, 0, SWP_NOSIZE Or SWP_NOMOVE
End Sub

Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.