Disabling close button in UserForm VBA

Alright, you’ve built an amazing Userform for your user, which works perfectly on every single function. A master piece of software! But, something remains out of your control, a simple click and everything is lost due to… the infamous close button! Ok, you know there is an easy and clever way to avoid this situation, handling the Query_Close event and the Cancel parameter.

So far so good, but… why do you and your user need this button there? Until this question remains unsolved, let’s look to another way to set our lives free about this problem.

Uma necessidade comum em alguns sistemas VBA é evitar que o usuário feche o form involuntariamente. A forma mais comum é captura o evento Query_Close e alterar o valor do parâmetro Cancel.

Porém algumas vezes é necessário que o botão de fechamento nem apareça para alterar. Para isso, basta colocar o código abaixo em um UserForm VBA. Os eventos Initialize e Query_Close já criados tratam de remover o botão do UserForm.

Private Declare Function FindWindowA Lib "USER32" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetWindowLongA Lib "USER32" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLongA Lib "USER32" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
 
Private Sub UserForm_Initialize()
    Dim hwnd As Long
    hwnd = FindWindowA(vbNullString, Me.Caption)
    SetWindowLongA hwnd, -16, GetWindowLongA(hwnd, -16) And &HFFF7FFFF
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    Dim hwnd As Long
    hwnd = FindWindowA(vbNullString, Me.Caption)
    SetWindowLongA hwnd, -16, GetWindowLongA(hwnd, -16) Or &H80000
End Sub

É bom atentar que desaparecer com o botão não desativa o uso do atalho Alt+F4 que fecha a janela.

Bom proveito!

Tomás Vásquez
http://www.tomasvasquez.com.br

Comentários

comentários

3 thoughts on “Disabling close button in UserForm VBA”

  1. Tenho uma planilha que após estar aberta por mais 10 minutos, aproximadamente, é apresentado o erro de “controlsource”, propriedade de um formulario que foi criado atravé no VBA, esse erro só deixa de existir se eu fechar a planilha e abri-la novamente.
    Alguem pode me ajudar?

  2. Amigo, achei muito util esta sua funcao, mas estou encontrando dificuldade em fazer ela funcionar no windows 64, ela nao reconhece o user32

    poderia me ajudar?
    Abraços!
    Dante

Comments are closed.