Vba excel userform убрать кнопку закрыть

Добрый вечер, Владимир.
Не боитесь, что из-за того, что код там для старого Excel, а выясниться, что у ТС Excel 64бит, то вы будете две страницы объяснять, как это адаптировать? ;)

Цитата
govorun написал:
как убрать кнопку закрытия формы

неужто на форуме ну

ничегошеньки

нет? Про инет и не упоминаю.

You can work it out from the following snippets:

Select the cmdClose button
On the Menu bar, choose View | Code
Where the cursor is flashing, enter the following code:

Private Sub cmdClose_Click()
  Unload Me
End Sub

On the Menu bar, choose View | Object, to return to the UserForm.

To allow users to close the form by pressing the Esc key:

Select the cmdClose button
In the Properties window, change the Cancel property to True

To prevent users from closing the form by clicking the X button

When the UserForm is opened, there is an X at the top right. In addition to using the Close Form button, people will be able to close the form by using the X. If you want to prevent that, follow these steps.

Right-click on an empty part of the UserForm
Choose View | Code
From the Procedure dropdown, at the top right, choose QueryClose

Where the cursor is flashing, paste the highlighted code from the following sample

Private Sub UserForm_QueryClose(Cancel As Integer, _
  CloseMode As Integer)
  If CloseMode = vbFormControlMenu Then
    Cancel = True
    MsgBox "Please use the Close Form button!"
  End If
End Sub

On the Menu bar, choose View | Object, to return to the UserForm.
Now, if someone clicks the X in the UserForm, they’ll see your message.

from http://www.contextures.com/xlUserForm01.html

While working on a project recently, I thought about hiding the [X] close button which is at the top of the VBA UserForm.  I managed to identify three options for achieving this.  If you are thinking about the same thing, then this post will give you the answers you’re looking for.

To hide, or not to hide, that is the question

Before we start looking at the three options, I want to cover the most critical question of all: should we hide a UserForm’s close button?

The Close Button

The close button is a recognized part of the Windows environment.  Pretty much every application uses a cross at the top right corner to close a window.  Therefore, based on their experience of other applications, all users already know what the cross should do.  It doesn’t matter which country the user is in or what language they speak, it is a universally understood icon to close a window.  Therefore you should be asking yourself why you want to hide the close button at all.  With this in mind,  I would say that generally the close button should not be hidden or disabled.

However, there are some circumstances where we may want to break this general rule.  One such example is a progress bar.  If the user closes a progress bar, they may not know when the macro has finished running, or how long is left.  Therefore, it might be useful to hide the close button in this scenario.

By default, the close button will unload a UserForm, but it can be adapted to have a custom close procedure.  As we can control this functionality, it may be better to control it rather than hide or disable it.

About Windows API codes

Of the three solutions, two of them rely on Windows API calls.  These are where the VBA code makes use of functions which are not part of Excel, but part of the main Windows application.  As this is complicated stuff, I will not go through it in detail here.  But the key points to note about the Windows API codes are:

  • They will not work on a Mac, only on Windows.  So if designing for Windows and Mac, you will need to identify which platform is used and adapt the code accordingly.
  • The code sections marked “Include this code at the top of the module” must be included before any other Subs or Functions are declared, and must be below the Option Explicit statement (if you have one).

3 Options for disabling/hiding a UserForm close button

If you are still intent on hiding or disabling the close button, then read on to understand the three options.

(1) The unobvious disable with a message box

This first option is the worst of the three. It does not disable or hide the close button, but prevents the user from using it to close the window.

Even though it is the worst option, it is the easiest to use and understand.  The following code can be used within the UserForm’s QueryClose event.

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)

If CloseMode = vbFormControlMenu Then

    Cancel = True
    MsgBox "Please use the Close button to close the form", vbOKOnly

End If

End Sub

If the user clicks on the close button, the following message box will appear.

VBA MsgBox

This is effectively disabling the close button, as the UserForm will not close.  But from a user’s perspective, this solution is just frustrating.  Why would there be a button which doesn’t do anything apart from telling us it doesn’t do anything?  This is why it’s not a great option.

(2) Disable the close button (Windows API)

The second option will disable the close button; it will be visible, but will be greyed-out and cannot be clicked.

The first image below shows the close button when it is enabled; the second image shows the close button when it is disabled.

Enabled and disabled close buttons

From a user’s perspective, this option is better than the first, but still not great.  What is the point of a button which cannot be clicked; it just creates confusion?

Basic code

The code below should be copied into a new standard module and must be included before any other code, but after the Option Explicit statement (if there is one).

'Include this code at the top of the module
Private Const GWL_STYLE = -16
Private Const WS_CAPTION = &HC00000
Private Const WS_SYSMENU = &H80000
Private Const SC_CLOSE = &HF060

#If VBA7 Then

    Private Declare PtrSafe Function FindWindowA _
        Lib "user32" (ByVal lpClassName As String, _
        ByVal lpWindowName As String) As Long
    Private Declare PtrSafe Function DeleteMenu _
        Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, _
        ByVal wFlags As Long) As Long
    Private Declare PtrSafe Function GetSystemMenu _
        Lib "user32" (ByVal hWnd As Long, ByVal bRevert As Long) As Long
        
#Else

    Private Declare Function FindWindowA _
        Lib "user32" (ByVal lpClassName As String, _
        ByVal lpWindowName As String) As Long
    Private Declare Function DeleteMenu _
        Lib "user32" (ByVal hMenu As Long, _
        ByVal nPosition As Long, ByVal wFlags As Long) As Long
    Public Declare Function GetSystemMenu _
        Lib "user32" (ByVal hWnd As Long, ByVal bRevert As Long) As Long
        
#End If
'Include this code in the same module as the API calls above
Public Sub CloseButtonSettings(frm As Object, show As Boolean)

Dim windowHandle As Long
Dim menuHandle As Long
windowHandle = FindWindowA(vbNullString, frm.Caption)

If show = True Then

    menuHandle = GetSystemMenu(windowHandle, 1)

Else

    menuHandle = GetSystemMenu(windowHandle, 0)
    DeleteMenu menuHandle, SC_CLOSE, 0&

End If

End Sub

The code examples above create reusable functionality to enable or disable the close button.  The CloseButtonSettings subprocedure can now be called from any other module.   There are two arguments required:

  • frm – a reference to the UserForm for which the close button should be enabled/disabled
  • show – a True or False value where True = enable the close button and False = disable the close button

Disable the close button on UserForm initialize

If inserted into the UserForm’s initialize event it will disable the button when the form is created.

Private Sub UserForm_Initialize()

Call CloseButtonSettings(Me, False)

End Sub

Disable or enable the close button at any point

The close button can be enabled or disabled as and when required with the following macros:

Disable the close button

Sub DisableClose()

Call CloseButtonSettings(frmMyUserForm, False)

End Sub

Enable the close button

Sub EnableClose()

Call CloseButtonSettings(frmMyUserForm, True)

End Sub

(3) Hide system menu (Windows API)

The third option is to hide the system menu section of the window.  The System menu section includes the maximize, minimize and close buttons.  The screenshot below shows the close button is not visible.

API No close button

By hiding the system menu section, we are also removing the ability to see the minimize and maximize buttons.  By default a UserForm does not have these buttons visible (separate Windows API calls are required to enable this), therefore this is probably a good option in 99.9% of circumstances.

Basic Code

The code below should be copied into a new standard module and must be included before any other code, but after the Option Explicit statement (if there is one).

'Include this code at the top of the module
Private Const GWL_STYLE = -16
Private Const WS_CAPTION = &HC00000
Private Const WS_SYSMENU = &H80000

#If VBA7 Then

    Private Declare PtrSafe Function GetWindowLong _
        Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, _
        ByVal nIndex As Long) As Long
    Private Declare PtrSafe Function SetWindowLong _
        Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, _
        ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
    Private Declare PtrSafe Function FindWindowA _
        Lib "user32" (ByVal lpClassName As String, _
        ByVal lpWindowName As String) As Long
    Private Declare PtrSafe Function DrawMenuBar _
        Lib "user32" (ByVal hWnd As Long) As Long
        
#Else

    Private Declare Function GetWindowLong _
        Lib "user32" Alias "GetWindowLongA" ( _
        ByVal hWnd As Long, ByVal nIndex As Long) As Long
    Private Declare Function SetWindowLong _
        Lib "user32" Alias "SetWindowLongA" ( _
        ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
    Private Declare Function FindWindowA _ 
        Lib "user32" (ByVal lpClassName As String, _
        ByVal lpWindowName As String) As Long
    Private Declare Function DrawMenuBar _
        Lib "user32" (ByVal hWnd As Long) As Long
  
#End If
'Include this code in the same module as the API calls above
Public Sub SystemButtonSettings(frm As Object, show As Boolean)
Dim windowStyle As Long
Dim windowHandle As Long

windowHandle = FindWindowA(vbNullString, frm.Caption)
windowStyle = GetWindowLong(windowHandle, GWL_STYLE)

If show = False Then

    SetWindowLong windowHandle, GWL_STYLE, (windowStyle And Not WS_SYSMENU)

Else

    SetWindowLong windowHandle, GWL_STYLE, (windowStyle + WS_SYSMENU)

End If

DrawMenuBar(windowHandle)

End Sub

These codes create reusable functionality to show or hide the buttons.  The SystemButtonSettings subprocedure can be called from any other module.   There are two arguments required

  • frm – a reference to the UserForm for which the close button should be shown/hidden
  • show – a True or False value where True = show the system menu and False = hide the system menu

Hide the system menu buttons on UserForm initialize

If inserted into the UserForm’s initialize event it will disable the button when the form is created.

Private Sub UserForm_Initialize()

Call SystemButtonSettings(Me, False)

End Sub

Show or hide the close button at any point

The close button can be shown or hidden as and when required using the following macros.

Hide the close button

Sub HideClose()

Call SystemButtonSettings(frmMyUserForm, False)

End Sub

Show the close button

Sub ShowClose()

Call SystemButtonSettings(frmMyUserForm, True)

End Sub

Download the example file

Want to see these examples working?  Then download the example file.


Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

Sometimes it may be desirable to disable the close button [X] on a userform in Excel or Word. For example, with a form where the user always has to fill in something before it can be closed or with a form with a progress bar. There may also be an aesthetic reason to hide the close button.

remove close button from form

What often happens in practice is to disable the operation of the close button using the UserForm_QueryClose event. This can be done as follows, for example:

Private Sub Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = 0 Then
        Cancel = True
        MsgBox "The close button [X] is disabled.", vbCritical, "Close button disabled"
    End If
End Sub

This works in itself, but in terms of user experience this is of course not good. Users click the close button and are then notified that this is not possible. It is better to hide the close button so that users do not have the option to click the close button.

By default you cannot disable the close button in a form, but it is possible using Windows API calls. To do this, put the code below in a separate module:

Private Const GWL_STYLE As Long = -16
Private Const WS_SYSMENU As Long = &H80000

#If VBA7 Then
    Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
    #If Win64 Then
        Private Declare PtrSafe Function GetWindowLong Lib "user32" Alias "GetWindowLongPtrA" (ByVal hWnd As LongPtr, ByVal nIndex As Long) As LongPtr
        Private Declare PtrSafe Function SetWindowLong Lib "user32" Alias "SetWindowLongPtrA" (ByVal hWnd As LongPtr, ByVal nIndex As Long, ByVal dwNewLong As LongPtr) As LongPtr
    #Else
        Private Declare PtrSafe Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As LongPtr, ByVal nIndex As Long) As LongPtr
        Private Declare PtrSafe Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As LongPtr, ByVal nIndex As Long, ByVal dwNewLong As LongPtr) As LongPtr
    #End If
#Else
    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
    Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
    Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
#End If

Public Sub RemoveCloseButton(frm As Object)
    #If VBA7 Then
        Dim lStyle As LongPtr, lFrmHandle As LongPtr
    #Else
        Dim lStyle As Long, lFrmHandle As Long
    #End If
    lFrmHandle = FindWindow("ThunderDFrame", frm.Caption)
    lStyle = GetWindowLong(lFrmHandle, GWL_STYLE)
    lStyle = lStyle And Not WS_SYSMENU
    SetWindowLong lFrmHandle, GWL_STYLE, lStyle
End Sub

You can use this in a userform in the UserForm_Initialize or UserForm_Activate event:

Private Sub UserForm_Initialize()
    RemoveCloseButton Me
End Sub

If, while opening a form, the caption of the form is dynamically changed using VBA, this call must be placed after this change.

Make sure that there is a button on the form with which the form can be closed, before the close button is hidden. Otherwise the form can no longer be closed!

This code works only in Windows and also works in 64 bit Office versions.

Questions / suggestions

Hopefully, this article helped you remove the close button from a VBA Userform. If you have any questions about this topic or suggestions for improvement, please post a comment below.

Содержание

  1. Как убрать заголовок у UserForm VBA
  2. Hide or disable a VBA UserForm [X] close button
  3. To hide, or not to hide, that is the question
  4. About Windows API codes
  5. 3 Options for disabling/hiding a UserForm close button
  6. (1) The unobvious disable with a message box
  7. (2) Disable the close button (Windows API)
  8. Basic code
  9. Disable the close button on UserForm initialize
  10. Disable or enable the close button at any point
  11. (3) Hide system menu (Windows API)
  12. Basic Code
  13. Hide the system menu buttons on UserForm initialize
  14. Show or hide the close button at any point
  15. Download the example file
  16. Hide close [X] button on excel vba userform for my progress bar
  17. 6 Answers 6

Как убрать заголовок у UserForm VBA

Иногда при разработке интерфейсов программы с помощью форм пользователя(UserForm) бывает необходимо запретить закрытие формы крестиком. Причин много: например на форме много элементов выбора и пользователь не должен просто закрывать форму крестиком, не выбрав что-то конкретное. Или может форма должна висеть постоянно на листе до тех пор, пока программа не сделает все необходимые действия и т.д.
Варианта два
Вариант 1
Можно просто запретить закрывать форму. Это значит, что после нажатия на крестик ничего не произойдет. Для этого надо перейти в модуль формы и на событие QueryClose прописать такой код:

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) If CloseMode = 0 Then ‘CloseMode = 0 — попытка закрыть форму крестиком Cancel = True ‘даем VBA понять, что надо отменить закрытие формы End If End Sub

данный код не даст закрыть форму нажатием на крестик, но если форма выгружается другими методами(вроде Unload) — форма закроется. За это отвечает параметр CloseMode, который может принимать следующие значения:

  • 0 или vbFormControlMenu — попытка закрытия формы пользователем через элемент управления крестик
  • 1 или vbFormCode — закрытие формы через выгрузку методом Unload
  • 2 или vbAppWindows — завершение сеанса Windows(в кодах VBA практически не используется)
  • 3 или vbAppTaskManager — завершение программы через диспетчер задач(в кодах VBA практически не используется)

Можно(скорее даже нужно!) дать понять пользователю, что он должен сделать что-то конкретное для закрытия формы и что крестиком это сделать нельзя, чтобы он не нервничал и не пытался завершить работу Excel через Clt+Alt+Delete;

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) If CloseMode = 0 Then ‘CloseMode = 0 — попытка закрыть форму крестиком MsgBox «Вы должны нажать на кнопку в центре, чтобы закрыть форму», vbInformation, «www.excel-vba.ru» Cancel = True ‘даем VBA понять, что надо отменить закрытие формы End If End Sub

Теперь при попытке закрыть форму крестиком пользователь увидит сообщение с инструкцией.

Вариант 2
Но порой надо не просто запретить закрывать форму — но и для эстетики убрать заголовок с крестиком вообще — чтобы не смущал пользователя. Здесь чуть посложнее — придется применить функции API. Код надо будет помещать уже на инициализацию формы(событие Initialize), а не на закрытие(QueryClose). Следующий код необходимо будет поместить в самое начало модуля той формы, меню которой требуется убрать(первой строкой или сразу после строк деклараций, таких как Option Explicit, Option Base, Option Compare Text):

‘константы для функций API Private Const GWL_STYLE As Long = -16& ‘для установки нового вида окна Private Const GWL_EXSTYLE = -20& ‘для расширенного стиля окна Private Const WS_CAPTION As Long = &HC00000 ‘определяет заголовок Private Const WS_BORDER As Long = &H800000 ‘определяет рамку формы ‘Функции API, применяемые для поиска окна и изменения его стиля #If VBA7 Then Private Declare PtrSafe Function SetWindowLong Lib «User32» Alias «SetWindowLongA» (ByVal hwnd As LongPtr, ByVal nIndex As Long, ByVal dwNewLong As LongPtr) As LongPtr Private Declare PtrSafe Function GetWindowLong Lib «User32» Alias «GetWindowLongA» (ByVal hwnd As LongPtr, ByVal nIndex As Long) As LongPtr Private Declare PtrSafe Function FindWindow Lib «User32» Alias «FindWindowA» (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr Private Declare PtrSafe Function DrawMenuBar Lib «User32» (ByVal hwnd As LongPtr) As Long #Else Private Declare Function SetWindowLong Lib «User32» Alias «SetWindowLongA» (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long Private Declare Function GetWindowLong Lib «User32» Alias «GetWindowLongA» (ByVal hwnd As Long, ByVal nIndex As Long) As Long Private Declare Function FindWindow Lib «user32.dll» Alias «FindWindowA» (ByVal lpClassName As String, ByVal lpWindowName As String) As Long Private Declare Function DrawMenuBar Lib «user32.dll» (ByVal hwnd As Long) As Long #End If

Это константы и функции API, которые и будут делать основную работу по удалению меню. Теперь останется на событие инициализации формы применить все эти функции:

Private Sub UserForm_Initialize() Dim ihWnd, hStyle ‘ищем окно формы среди всех открытых окон If Val(Application.Version) С легкой руки моего старого друга и модератора нашего форума ЮрияМ дополняю статью еще одним кодом. Если на запуск формы применить такой код:

Private Sub UserForm_Initialize() Dim ihWnd, hStyle ‘ищем окно формы среди всех открытых окон If Val(Application.Version) ВАЖНО: Применяя любой из подходов советую заранее продумать как форма будет вообще закрываться, в том числе в режиме отладки программы. Т.к. если просто вставить этот код, то сами же не сможете закрыть форму — только завершением выполнения кода через RunReset.

Во вложении найдете все описанные варианты отображения форм:

Tips_Macro_DontCloseFormOnMenu.xls (77,5 KiB, 1 888 скачиваний)

Статья помогла? Поделись ссылкой с друзьями!

Источник

Hide or disable a VBA UserForm [X] close button

While working on a project recently, I thought about hiding the [X] close button which is at the top of the VBA UserForm. I managed to identify three options for achieving this. If you are thinking about the same thing, then this post will give you the answers you’re looking for.

To hide, or not to hide, that is the question

Before we start looking at the three options, I want to cover the most critical question of all: should we hide a UserForm’s close button?

The close button is a recognized part of the Windows environment. Pretty much every application uses a cross at the top right corner to close a window. Therefore, based on their experience of other applications, all users already know what the cross should do. It doesn’t matter which country the user is in or what language they speak, it is a universally understood icon to close a window. Therefore you should be asking yourself why you want to hide the close button at all. With this in mind, I would say that generally the close button should not be hidden or disabled.

However, there are some circumstances where we may want to break this general rule. One such example is a progress bar. If the user closes a progress bar, they may not know when the macro has finished running, or how long is left. Therefore, it might be useful to hide the close button in this scenario.

By default, the close button will unload a UserForm, but it can be adapted to have a custom close procedure. As we can control this functionality, it may be better to control it rather than hide or disable it.

About Windows API codes

Of the three solutions, two of them rely on Windows API calls. These are where the VBA code makes use of functions which are not part of Excel, but part of the main Windows application. As this is complicated stuff, I will not go through it in detail here. But the key points to note about the Windows API codes are:

  • They will not work on a Mac, only on Windows. So if designing for Windows and Mac, you will need to identify which platform is used and adapt the code accordingly.
  • The code sections marked “Include this code at the top of the module” must be included before any other Subs or Functions are declared, and must be below the Option Explicit statement (if you have one).

3 Options for disabling/hiding a UserForm close button

If you are still intent on hiding or disabling the close button, then read on to understand the three options.

(1) The unobvious disable with a message box

This first option is the worst of the three. It does not disable or hide the close button, but prevents the user from using it to close the window.

Even though it is the worst option, it is the easiest to use and understand. The following code can be used within the UserForm’s QueryClose event.

If the user clicks on the close button, the following message box will appear.

This is effectively disabling the close button, as the UserForm will not close. But from a user’s perspective, this solution is just frustrating. Why would there be a button which doesn’t do anything apart from telling us it doesn’t do anything? This is why it’s not a great option.

(2) Disable the close button (Windows API)

The second option will disable the close button; it will be visible, but will be greyed-out and cannot be clicked.

The first image below shows the close button when it is enabled; the second image shows the close button when it is disabled.

From a user’s perspective, this option is better than the first, but still not great. What is the point of a button which cannot be clicked; it just creates confusion?

Basic code

The code below should be copied into a new standard module and must be included before any other code, but after the Option Explicit statement (if there is one).

The code examples above create reusable functionality to enable or disable the close button. The CloseButtonSettings subprocedure can now be called from any other module. There are two arguments required:

  • frm – a reference to the UserForm for which the close button should be enabled/disabled
  • show – a True or False value where True = enable the close button and False = disable the close button

Disable the close button on UserForm initialize

If inserted into the UserForm’s initialize event it will disable the button when the form is created.

Disable or enable the close button at any point

The close button can be enabled or disabled as and when required with the following macros:

Disable the close button

Enable the close button

The third option is to hide the system menu section of the window. The System menu section includes the maximize, minimize and close buttons. The screenshot below shows the close button is not visible.

By hiding the system menu section, we are also removing the ability to see the minimize and maximize buttons. By default a UserForm does not have these buttons visible (separate Windows API calls are required to enable this), therefore this is probably a good option in 99.9% of circumstances.

Basic Code

The code below should be copied into a new standard module and must be included before any other code, but after the Option Explicit statement (if there is one).

These codes create reusable functionality to show or hide the buttons. The SystemButtonSettings subprocedure can be called from any other module. There are two arguments required

  • frm – a reference to the UserForm for which the close button should be shown/hidden
  • show – a True or False value where True = show the system menu and False = hide the system menu

If inserted into the UserForm’s initialize event it will disable the button when the form is created.

Show or hide the close button at any point

The close button can be shown or hidden as and when required using the following macros.

Hide the close button

Show the close button

Download the example file

Want to see these examples working? Then download the example file.

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).

Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:

Источник

Hide close [X] button on excel vba userform for my progress bar

I created a userform to show a progress bar when the macro is still importing sheets

The problem is the user can press the red [X] button that will close and interrupt the processing done.

Is there a way to hide this red button of doom so that potential users don’t have any confusing buttons to click while it runs.

I have tried this

and I used this on userform_initialize

I am getting this error message

this code was taken from here. I don’t know what I’m doing wrong and I already removed the comments. This is the simplest code that I found so I would like to integrate it to my userform. Any help is appreciated.

6 Answers 6

Below is a routine that you can call like this:

or from within your form:

Here’s the code you’ll need:

You can work it out from the following snippets:

Select the cmdClose button On the Menu bar, choose View | Code Where the cursor is flashing, enter the following code:

On the Menu bar, choose View | Object , to return to the UserForm.

To allow users to close the form by pressing the Esc key:

Select the cmdClose button In the Properties window, change the Cancel property to True

To prevent users from closing the form by clicking the X button

When the UserForm is opened, there is an X at the top right. In addition to using the Close Form button, people will be able to close the form by using the X. If you want to prevent that, follow these steps.

Right-click on an empty part of the UserForm Choose View | Code From the Procedure dropdown, at the top right, choose QueryClose

Where the cursor is flashing, paste the highlighted code from the following sample

On the Menu bar, choose View | Object , to return to the UserForm. Now, if someone clicks the X in the UserForm, they’ll see your message.

Источник

Понравилась статья? Поделить с друзьями:
  • Vba excel userform свернуть
  • Vba excel worksheet cell
  • Vba excel активация бесплатно
  • Vba excel workbook events
  • Vba excel userform на весь экран