1
votes

I am writing Excel 2007 VBA that uses Windows API calls to manage the Z-order of several userforms. I'm using the following procedure to retrieve the Windows API handle for the userforms frmUserDataWS and frmUserDataLT:

Sub TestZOrder()

Dim h_lngWndExcel As Long
Dim h_lngUserDataWSWnd As Long
Dim h_lngUserDataLTWnd As Long

'frmUserDataLT.Show vbModeless
'frmUserDataWS.Show vbModeless

h_lngWndExcel = Application.hwnd
h_lngUserDataLTWnd = FindWindow("ThunderDFrame", frmUserDataLT.Caption)
h_lngUserDataWSWnd = FindWindow("ThunderDFrame", frmUserDataWS.Caption)

Debug.Print "Excel Application window handle ... " & h_lngWndExcel
Debug.Print "UserDataLT window handle ... " & h_lngUserDataLTWnd
Debug.Print "UserDataWS window handle ... " & h_lngUserDataWSWnd

End Sub

I expected the variable h_lngWndExcel to return a handle value because it's the handle variable for the main Excel window. But I was surpised to see a value for the h_lngUserDataWSWnd and the h_lngUserDataLTWnd variables since these are handle variables for the two userforms, and I don't load either userform (the .Show statement for both userforms have been commented out). I ran the procedure code above after first launching the Excel workbook where the above procedure resides, enabling macros, and running the procedure.

I expected zeros for the userform handle variables, but instead got actual handle values. I'd like to understand why the userform handles didn't return zeros since neither userform was loaded. Is it because Windows (Windows 7, 64-bit in my case) generates a handle for userforms even if they have never been shown or loaded? Do userform handles get generated when the VBA is first initialized and not when the userform is shown?

1
You do load them - as soon as you refer to them.Rory
Thanks, Rory, for the explanation. That helps a bunch! Can you post your comment as an answer so I can market it as such? Thanks.Bill Vallance

1 Answers

1
votes

Userforms in VBA are auto-instantiating so as soon as you use frmUserDataLT.Caption you actually load the form, which is why it has a handle.