Tuesday, September 18, 2012

How to check whether Cancel has been pressed in the InputBox.

This is a method to identify that the cancel button has been pressed in the InputBox.
InputBox returns vbNullString if the cancel button is clicked.
If the string is vbNullString, StrPtr will be 0.

Sub main()
    Dim sTemp As String
    sTemp = InputBox("What's the value?")
    If StrPtr(sTemp) = 0 Then
        MsgBox "Cancel was clicked"
    End If
End Sub

How to retrieve the Window handle of the UserForm in VBA.

Here is how to get the window handle of UserForm with VBA.

Unlike VB6, VBA forms do not have the hWnd property.
Therefore, in general, you will use the FindWindow API to reverse lookup from the form's Caption.

In general, you can get your own hWnd in a userform like this:

Private Declare PtrSafe Function FindWindow Lib "User32.dll" Alias "FindWindowA" _
  (ByVal ClassName As String, ByVal WindowName As String) As LongPtr

Public Property Get hWnd() As LongPtr
    hWnd = FindWindow("ThunderDFrame", Me.Caption)
End Property
However, strictly speaking, in the case where a UserForm with the same Caption exists, 
there is no guarantee that this code could get the hWnd of the desired UserForm.
The same is true when multiple instances of Excel.exe open the same workbook.

You probably don't need to consider these rare cases, but if you do, the code below will do the trick.

Private Declare PtrSafe Function WindowFromAccessibleObject Lib "oleacc.dll" _
  (ByVal IAcessible As Object, ByRef HWND As LongPtr) As Long

Public Property Get HWND() As LongPtr
    WindowFromAccessibleObject Me, HWND
End Property

*
FindWindow function has specifications at https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-findwindowa .
WindowFromAccessibleObject function has specifications at https://docs.microsoft.com/ja-jp/windows/win32/api/oleacc/nf-oleacc-windowfromaccessibleobject .