简体   繁体   中英

Set Focus on an Excel User Form Using VBA

I got my project 95% done but a small issue remains. My code, run from a user form, opens a PDF document with its first line, identifies its window in the second and moves and resizes that window in the third.

    ActiveWorkbook.FollowHyperlink Mail(0) & Mail(Me.Tag)
    Wnd = FindWindow(vbNullString, AcrobatWindowID(Mail(Me.Tag)))
    SetWindowPos Wnd, HWND_TOP, 1950, 10, 1100, 1300, SWP_NOACTIVATE

At the end of this operation the user form is dimmed out. The focus seems to remain with the PDF. That doesn't really matter because the form is fully developed and I can click on it or the PDF to activate either, just the way I wanted.

Nevertheless I tried to give the focus to the form and then to a particular control. I succeeded in finding the Excel window but failed to set the focus on the form, not to mention the control. In fact, I don't know how to check if I succeeded in setting the focus on the Excel window. I used this code in my attempt of whose syntax I'm not sure.

Public Const SWP_NOMOVE = &H2           ' ignore cx and cy
Public Const SWP_NOSIZE = &H1           ' ignore X and Y

SetWindowPos Wnd, HWND_TOP, 0, 0, 0, 0, (SWP_NOMOVE + SWP_NOSIZE)

Anyway, the form remains dimmed out. Does anyone have advice for me?

In order to obtain the form handler, you should proceed in this way:

  1. Use API GetActiveWindow and create a Private variable on top of the form code module (in the declarations area):
Option Explicit

Private Declare PtrSafe Function GetActiveWindow Lib "user32" () As LongPtr

Private frmHwnd as LongPtr
  1. Insert the next code line in the UserForm_Initialize event:
frmHwnd = GetActiveWindow

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