简体   繁体   中英

userform always ontop after add new workbook excel vba

I got one userform with a commandbutton on it, this button is use to create a new workbook. I want this userform on top of the new created workbook after click the button. Any idea?(For excel 2007, userform is always on top, but not for excel 2016 )

Private Sub CommandButton1_Click()
Workbooks.Add

End Sub

Try placing the following snippet on top of the userform's code module.

Option Explicit
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal clsName As String, ByVal wndName As String) As Long
Private Declare PtrSafe Function SetParent Lib "user32" (ByVal hChild As Long, ByVal hParent As Long) As Long

Private Sub CommandButton1_Click()
  Static h As Long
  If h <= 0 Then h = FindWindow("ThunderDFrame", Me.Caption)
  If h <= 0 Then Exit Sub
  Dim wb As Workbook: Set wb = Workbooks.Add
  SetParent h, Application.Windows(wb.Name).hwnd
  wb.Activate
End Sub

This will make the new workbook the Parent of the user-form. It implies that the form will unload when you close the new workbook. If your goal is to keep the form alive for whatever workbook or worksheet is active, some other techniques can be used, maybe the easiest of which is by handling the Workbook_SheetActivate event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM