When creating a VBA UserForm, we generally set it to a specific size. Most other forms and windows within the Excel and Windows environments do not have a fixed sized; they can be resized by the user. With a bit of coding magic, we can achieve a similar resizing effect for our VBA UserForms. This post will show you how.
There are two solutions presented below, a Windows API method and a VBA only method. Of the two, the Windows API solution has a smoother, more integrated feel for the user, but it will only work on Windows. If your code is expected to work on Windows and Mac, then using the VBA solution is the better option.
Windows API Solution
Windows API codes make use of special functions which are not part of Excel or VBA, but part of the main Windows application. The topic of Windows API codes is too big to discuss here, but by following the instructions below you can still get the code working, even if you don’t have a full understanding of why it works.
Remember, Windows API codes will only work on Windows.
How does it work?
A brief overview of how the process works will help with understanding what the code below does.
- Change the Windows setting to enable the UserForm to be resized.
- On the UserForm use the Resize event to capture when the form is resized.
- The objects’ size or position changes after each resize event.
Setting up the Windows API code
Copy the following code into a new standard module. It must be included at the top of the module before any functions or subprocedures, but below the Option Explicit statement (if there is one).
Public Const GWL_STYLE = -16 Public Const WS_CAPTION = &HC00000 Public Const WS_THICKFRAME = &H40000 #If VBA7 Then Public Declare PtrSafe Function GetWindowLong _ Lib "user32" Alias "GetWindowLongA" ( _ ByVal hWnd As Long, ByVal nIndex As Long) As Long Public Declare PtrSafe Function SetWindowLong _ Lib "user32" Alias "SetWindowLongA" ( _ ByVal hWnd As Long, ByVal nIndex As Long, _ ByVal dwNewLong As Long) As Long Public Declare PtrSafe Function DrawMenuBar _ Lib "user32" (ByVal hWnd As Long) As Long Public Declare PtrSafe Function FindWindowA _ Lib "user32" (ByVal lpClassName As String, _ ByVal lpWindowName As String) As Long #Else Public Declare Function GetWindowLong _ Lib "user32" Alias "GetWindowLongA" ( _ ByVal hWnd As Long, ByVal nIndex As Long) As Long Public Declare Function SetWindowLong _ Lib "user32" Alias "SetWindowLongA" ( _ ByVal hWnd As Long, ByVal nIndex As Long, _ ByVal dwNewLong As Long) As Long Public Declare Function DrawMenuBar _ Lib "user32" (ByVal hWnd As Long) As Long Public Declare Function FindWindowA _ Lib "user32" (ByVal lpClassName As String, _ ByVal lpWindowName As String) As Long #End If
This following code must be included within the same module as the code above but does not need to be directly below it.
Sub ResizeWindowSettings(frm As Object, show As Boolean) Dim windowStyle As Long Dim windowHandle As Long 'Get the references to window and style position within the Windows memory windowHandle = FindWindowA(vbNullString, frm.Caption) windowStyle = GetWindowLong(windowHandle, GWL_STYLE) 'Determine the style to apply based If show = False Then windowStyle = windowStyle And (Not WS_THICKFRAME) Else windowStyle = windowStyle + (WS_THICKFRAME) End If 'Apply the new style SetWindowLong windowHandle, GWL_STYLE, windowStyle 'Recreate the UserForm window with the new style DrawMenuBar windowHandle End Sub
The two code segments above create a reusable procedure which we can use to toggle the UserForm’s resize setting on or off. Anytime we want to turn on resizing for a UserForm, use the following:
Call ResizeWindowSettings(myUserForm, True)
To turn off resizing, use the following
Call ResizeWindowSettings(myUserForm, False)
Just replace myUserForm with the name of your form, or use Me if within the UserForm’s code module.
Setting up the UserForm
To illustrate the process, I’ve created a UserForm which looks like this:
There are just two elements:
- A ListBox called lstListBox
- A Button called cmdClose
Both of these elements should change when then UserForm resizes. lstListBox should change in size, but not in position while the cmdClose will change in position but not in size. To enable this to happen we need to know the position of these objects from the bottom and right of the UserForm. Provided we keep the same distance from the bottom and right it will appear that these items are moving in sync with the UserForm.
The code below must be included within the UserForm’s code module to function correctly.
To capture the initial bottom and right positions of the ListBox and Button, we set up some Private variables to hold the values.
Private lstListBoxBottom As Double Private lstListBoxRight As Double Private cmdCloseBottom As Double Private cmdCloseRight As Double
Now let’s set up what happens when the UserForm initializes.
Firstly, resizing is enabled by calling the code created in the Windows API section above. Secondly, we store the position of the objects in the private variables created above.
Private Sub UserForm_Initialize() 'Call the Window API to enable resizing Call ResizeWindowSettings(Me, True) 'Get the bottom right anchor position of the objects to be resized lstListBoxBottom = Me.Height - lstListBox.Top - lstListBox.Height lstListBoxRight = Me.Width - lstListBox.Left - lstListBox.Width cmdCloseBottom = Me.Height - cmdClose.Top - cmdClose.Height cmdCloseRight = Me.Width - cmdClose.Left - cmdClose.Width End Sub
Next, using the UserForm’s resize event, we change the size/position of ListBox and the Button:
- lstListBox changes height and width
- cmdCloses changes top and left position
Private Sub UserForm_Resize() On Error Resume Next 'Set the new position of the objects lstListBox.Height = Me.Height - lstListBoxBottom - lstListBox.Top lstListBox.Width = Me.Width - lstListBoxRight - lstListBox.Left cmdClose.Top = Me.Height - cmdCloseBottom - cmdClose.Height cmdClose.Left = Me.Width - cmdCloseRight - cmdClose.Width On Error GoTo 0 End Sub
That is it. You’ve now got the code you need. So fire up the UserForm and start resizing.
When the mouse hovers over the edge of the UserForm, the icon changes, just click and drag. With this method, resizing can happen on any side of the UserForm.
VBA only solution
The VBA solution makes use of mouse events to trigger when to change the height and width of the UserForm. Personally, I think it’s not as smooth as the Window API solution, but it is much easier to understand and can be used on a Mac too.
How does it work?
The VBA solution uses a different method of application to the Window API solution.
- The UserForm contains an object which when clicked records the position of the mouse.
- As the mouse moves, the UserForm and it’s objects are repositioned or resized based on the new mouse position.
- When the mouse button is released, movement ceases to adjust the size.
Setting up the UserForm
To illustrate the process, I have created anotherUserForm; it looks like this:
There are just three elements:
- ListBox called lstListBox
- Button called cmdClose
- Label called lblResizer
The lblResizer is a label which includes the “y” character from the Wingdings 3 font set. This displays as a small triangle in the bottom right corner to show the user where to click to resize the window. The Color and MousePointer properties are set as follows:
All of these elements, along with the UserForm itself will need to change when the mouse is clicked and moved whilst over the lblResizer object.
All the code must be contained within the UserForm’s code module.
We will set up some Private variables to hold the mouse position and click status, along with the minimum allowed window size.
Private resizeEnabled As Boolean Private mouseX As Double Private mouseY As Double Private minWidth As Double Private minHeight As Double
When initializing the UserForm, the code below will place the lblResizer into the bottom right corner, and set the minimum permitted window size.
Private Sub UserForm_Initialize() 'Position the resize icon lblResizer.Left = Me.InsideWidth - lblResizer.Width lblResizer.Top = Me.InsideHeight - lblResizer.Height minHeight = 125 minWidth = 125 End Sub
The following code triggers when the mouse clicks on the lblResizer icon. The code records that the icon has been clicked and the position of the mouse at that moment.
Private Sub lblResizer_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _ ByVal X As Single, ByVal Y As Single) 'The user clicked on the lblResizer resizeEnabled = True 'Capture the mouse position on click mouseX = X mouseY = Y End Sub
The following code triggers when the mouse moves while over the lblResizer.
Firstly, it will check that the window is larger than the minimum permitted size, and that mouse has been clicked. If both of these are True, the UserForm and the objects are re-positioned or resized based on the size of the mouse movement.
Private Sub lblResizer_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _ ByVal X As Single, ByVal Y As Single) 'Check if the UserForm is not resized too small Dim allowResize As Boolean allowResize = True If Me.Width + X - mouseX < minWidth Then allowResize = False If Me.Height + Y - mouseY < minHeight Then allowResize = False 'Check if the mouse clicked on the lblResizer and above minimum size If resizeEnabled = True And allowResize = True Then 'Resize/move objects based on mouse movement since click 'Resize the UserForm Me.Width = Me.Width + X - mouseX Me.Height = Me.Height + Y - mouseY 'Resize the ListBox lstListBox.Width = lstListBox.Width + X - mouseX lstListBox.Height = lstListBox.Height + Y - mouseY 'Move the Close Button cmdClose.Left = cmdClose.Left + X - mouseX cmdClose.Top = cmdClose.Top + Y - mouseY 'Move the Resizer icon lblResizer.Left = Me.InsideWidth - lblResizer.Width lblResizer.Top = Me.InsideHeight - lblResizer.Height End If End Sub
The following code triggers when the mouse button is released; the mouse movement ceases to resize the UserForm.
Private Sub lblResizer_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _ ByVal X As Single, ByVal Y As Single) 'The user un-clicked on the lblResizer resizeEnabled = False End Sub
That is it; we’re good to go. Open up the UserForm and start resizing.
In this example, the UserForm only resizes when the mouse clicks on the icon in the bottom right. We could add the ability to expand from the right, bottom, or left by using objects positioned just inside the edges of the UserForm.
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:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- 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.
- 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:
UserForm in Excel that can be resized by the user — they can click and drag the edges or corners of the form to change its size, just like with a regular window in the operating system.
Sections:
Make Form Resizable
Resize Event
Notes
Make Form Resizable
To do this, we need to place VBA code within a regular module and also within the Activate event for the UserForm.
Module Code
The below code goes into a regular module in the VBA window. (Alt + F11 to get to the VBA window and then Insert > Module.)
Private Declare Function GetForegroundWindow Lib "User32.dll" () As Long
Private Declare Function GetWindowLong _
Lib "User32.dll" Alias "GetWindowLongA" _
(ByVal hWnd As Long, _
ByVal nIndex As Long) _
As Long
Private Declare Function SetWindowLong _
Lib "User32.dll" Alias "SetWindowLongA" _
(ByVal hWnd As Long, _
ByVal nIndex As Long, _
ByVal dwNewLong As Long) _
As Long
Private Const WS_THICKFRAME As Long = &H40000
Private Const GWL_STYLE As Long = -16
Note: this code must go at the very top of the module before any other code!
The next section of code can be placed anywhere within the module.
Public Sub FormResizable()
Dim lStyle As Long
Dim hWnd As Long
Dim RetVal
hWnd = GetForegroundWindow
lStyle = GetWindowLong(hWnd, GWL_STYLE) Or WS_THICKFRAME
RetVal = SetWindowLong(hWnd, GWL_STYLE, lStyle)
End Sub
UserForm Code
Code must also be placed within the UserForm itself in order to work.
All you need to do is call FormResizable from the Activate event for the UserForm.
FormResizable
When you put the code into the Activate event for the UserForm, it will look like this:
Private Sub UserForm_Activate()
FormResizable
End Sub
If you already have code in the Activate event, just place FormResizable at the top of this section.
To learn more about events and how to use them, view our tutoral on UserForm Events.
Resize Event
Resizing a form without chaning anything within the form window is usually useless, as such, you can put code inside of the UserForm_Resize event that will adjust the properties of the controls in the form when the user resizes it, such as increasing the size of buttons or labels within the form when a user makes the form larger.
Notes
When a form is resized by the user, using the above code, once the form has been closed and opened again, it will default back to the original size.
Make sure to download the sample file to see this example in Excel.
Similar Content on TeachExcel
UserForm Events
Tutorial: Explanation of UserForm Events in Excel. This includes what they are, how to use them, and…
UserForm Controls
Tutorial: This tutorial gives you an overview of what a UserForm Control is and how to add them to y…
Scrollable UserForm
Tutorial: How to make a scrollable UserForm. This allows you to put scroll bars onto a form so that …
How to Resize Rows and Columns in Excel Quickly
Tutorial: Resizing rows and columns in Excel is an easy process. Simply left click in between the co…
Prevent Images and Shapes from Resizing or Moving in Excel
Tutorial:
How to stop Images and Shapes from resizing in Excel when you change the size of rows and…
Quickly Resize Multiple Columns or Rows at Once in Excel
Tutorial:
How to quickly resize multiple columns and rows at once in Excel. This avoids having to…
Subscribe for Weekly Tutorials
BONUS: subscribe now to download our Top Tutorials Ebook!
I am trying to resize a userform and its controls with VBA in order to accommodate different size monitors. Following is the code I am using which is based on Ron DeBruin’s code (http://www.rondebruin.nl/mac/mac022.htm).
In essence, the code is designed to scale the userform’s size and location together with all of its controls.
The problem is I’m getting an error (shown below) on execution
"Run-time error '-2147467259(80004005)': Method 'Properties' of object '_VBComponent' failed"
I tried replacing .Properties("Top")
with .Top
and I got the Object doesn't support this property or method
error.
Mr. DeBruin’s code makes since; but I am at a loss as to why it is not working. Any help would certainly be appreciated.
Sub ChangeUserFormAndControlsSize()
Dim AppUserform As Object
Dim FormControl As Object
Dim NameUserform As String
Dim SizeCoefficient As Single
SizeCoefficient = wsControls.Range("SizeCoefficient")
NameUserform = "form_APScheduler"
Set AppUserform = ThisWorkbook.VBProject.VBComponents(NameUserform)
With AppUserform
.Properties("Top") = .Properties("Top") * SizeCoefficient '*** ERROR OCCURS HERE
.Properties("Left") = .Properties("Left") * SizeCoefficient
.Properties("Height") = .Properties("Height") * SizeCoefficient
.Properties("Width") = .Properties("Width") * SizeCoefficient
End With
For Each FormControl In AppUserform.Designer.Controls
With FormControl
.Top = .Top * SizeCoefficient
.Left = .Left * SizeCoefficient
.Width = .Width * SizeCoefficient
.Height = .Height * SizeCoefficient
On Error Resume Next
.Font.Size = .Font.Size * SizeCoefficient
On Error GoTo 0
End With
Next FormControl
End Sub
hnk
2,1961 gold badge11 silver badges18 bronze badges
asked Jul 10, 2014 at 4:12
5
Based on your last comment, here is some example code showing how to change the properties at run time, without accessing the VBIDE.VBProject object. Of course, these changes will not persist.
Option Explicit
Sub testForm()
Dim UF As form_APScheduler
Dim FormControl As MSForms.Control
Dim SizeCoefficient As Double
SizeCoefficient = inputNumber("Scale Factor: ", "Form", 1)
Set UF = New form_APScheduler
With UF
.Top = .Top * SizeCoefficient
.Left = .Left * SizeCoefficient
.Width = .Width * SizeCoefficient
.Height = .Height * SizeCoefficient
End With
For Each FormControl In UF.Controls
With FormControl
.Top = .Top * SizeCoefficient
.Left = .Left * SizeCoefficient
.Width = .Width * SizeCoefficient
.Height = .Height * SizeCoefficient
On Error Resume Next
.Font.Size = .Font.Size * SizeCoefficient
On Error GoTo 0
End With
Next FormControl
UF.Show
Unload UF
End Sub
Function inputNumber(prompt As String, title As String, defValue As Variant) As Variant
inputNumber = Application.InputBox(prompt, title, defValue, , , , , 1)
End Function
answered Jul 12, 2014 at 15:48
Cool BlueCool Blue
6,4286 gold badges28 silver badges67 bronze badges
1
0 / 0 / 0 Регистрация: 22.12.2011 Сообщений: 27 |
|
1 |
|
22.12.2011, 14:55. Показов 13941. Ответов 19
В VB у Form есть свойство BorderStyle, которому можно присвоить значение Sizebale, а в VBA такому же свойству объекта UserForm можно присвоить только BorderStyleNone или BorderStyleSignle. Кроме этого, хотелось бы сделать окно без заголовка. Возможно ли?
0 |
1 / 1 / 1 Регистрация: 10.04.2011 Сообщений: 415 |
|
22.12.2011, 15:04 |
2 |
размеры формы меняются установкой требуемой ширины и высоты.
0 |
0 / 0 / 0 Регистрация: 22.12.2011 Сообщений: 27 |
|
22.12.2011, 16:44 [ТС] |
3 |
Нужно чтобы пользователь мог менять размеры окна.
0 |
1 / 1 / 1 Регистрация: 10.04.2011 Сообщений: 415 |
|
22.12.2011, 17:11 |
4 |
Драг-дропом? Боюсь, не прокатит. А где ты видел диалоговое окно с такими возможностями — там же элементы управления. Как вариант — сделай 4 кнопочки примерно так: http://www.mfco.ru/resform.zip
0 |
0 / 0 / 0 Регистрация: 22.12.2011 Сообщений: 27 |
|
22.12.2011, 17:32 [ТС] |
5 |
> А где ты видел диалоговое окно с такими возможностями
0 |
90 / 37 / 14 Регистрация: 03.11.2010 Сообщений: 429 |
|
22.12.2011, 19:58 |
6 |
Драг-дропом?-Можно сделать имитацию:
0 |
2 / 2 / 0 Регистрация: 23.04.2011 Сообщений: 159 |
|
27.12.2011, 14:42 |
7 |
Через API:
0 |
1 / 1 / 1 Регистрация: 10.04.2011 Сообщений: 415 |
|
27.12.2011, 15:42 |
8 |
Как ты файл прикрепляешь, поделись?
0 |
2 / 2 / 0 Регистрация: 23.04.2011 Сообщений: 159 |
|
27.12.2011, 16:37 |
9 |
Шутите или в серьезно?
0 |
2 / 2 / 0 Регистрация: 23.04.2011 Сообщений: 159 |
|
27.12.2011, 16:42 |
10 |
Sorry, в предыдущем ответе “В” опустить
0 |
0 / 0 / 0 Регистрация: 22.12.2011 Сообщений: 27 |
|
27.12.2011, 17:05 [ТС] |
11 |
Через API: Отлично! Именно то, что нужно. Просто я мало с API имел дело и сам не нашел бы нужных функций. Спасибо огромное!
0 |
1 / 1 / 1 Регистрация: 10.04.2011 Сообщений: 415 |
|
27.12.2011, 17:28 |
12 |
Шутите или серьезно? Конечно серьезно — нафига мне класть файлы на свой сервер, а потом ссылку давать? А указание на файл на локальном диске дает ошибку «только txt, zip, rar, gif, jpg, png», хотя ему даю rar-архив
0 |
2 / 2 / 0 Регистрация: 23.04.2011 Сообщений: 159 |
|
27.12.2011, 18:31 |
13 |
To Johny Walker: После известных изменении на форуме, когда я нажимаю на “Ответить” прямо попадаю в редактор новых сообщении, где наверху находится “Прикрепить файл”.
0 |
Alex77 |
||||
28.12.2011, 10:39 |
14 |
|||
Нужно чтобы пользователь мог менять размеры окна. А может вот так подойдёт:
При нажатии над формой (в данном случае левой, для правой «If Button = 2»), и удерживая кнопку двигать мышу — меняется размер формы. Безо всяких АПИ |
0 / 0 / 0 Регистрация: 22.12.2011 Сообщений: 27 |
|
29.12.2011, 12:47 [ТС] |
15 |
А может вот так подойдёт: Спасибо за идею! Только это я использую для изменения позиции окна. А изменяемые размеры и прочие своства лучше через API.
0 |
Alex77 |
|
03.01.2012, 08:26 |
16 |
Через API: Третий раз скачиваю, пробую. |
0 / 0 / 0 Регистрация: 22.12.2011 Сообщений: 27 |
|
03.01.2012, 13:06 [ТС] |
17 |
Через API: Третий раз скачиваю, пробую. Смотри аттач.
0 |
Alex77 |
|
03.01.2012, 15:26 |
18 |
Через API: Третий раз скачиваю, пробую. Смотри аттач. Собственно хоть скажите, что должно было происходить. |
0 / 0 / 0 Регистрация: 22.12.2011 Сообщений: 27 |
|
03.01.2012, 15:49 [ТС] |
19 |
Если отмечено WS_THICKFRAME, окно будет менять размеры, как обычно в Windows (перетаскиванием за рамку).
0 |
Alex77 |
|
04.01.2012, 21:53 |
20 |
Спасибо, разобрался. |
Amberalex Пользователь Сообщений: 111 |
здравствуйте! |
Amberalex Пользователь Сообщений: 111 |
Прошу большого прощения! не попал по кнопке телефона ((( и не знаю, как отредактировать предыдущее сообщение ((( |
ISergey Пользователь Сообщений: 78 |
свойства формы Height, Width позволят задать форме нужные размеры. |
Amberalex Пользователь Сообщений: 111 |
на этапе проектирования и в VBA — конечно. а как конечному пользователю изменить размер уже выведенной на экран формы? |
vikttur Пользователь Сообщений: 47199 |
Кнопочка вызывает формочку, а в формочке написано: «хочу размер от сих до сих!» |
Amberalex Пользователь Сообщений: 111 |
Оо, как будет сложно… к тому же пользователи не знают, какая ширина в пунктах им нужна, только подбором… |
vikttur Пользователь Сообщений: 47199 |
Почему в пунктах? Пускай вводит в килограммах, макрос сконвертирует |
vikttur Пользователь Сообщений: 47199 |
Каков смысл изменения размера? Если подогнать под размер монитора и выставить заранее заданное увеличение/уменьшение, можно только кнопочку без формочки. |
Amberalex Пользователь Сообщений: 111 |
Не понял вопроса… ну вот пользователь решил, что форма слишком большая, не всё он за ней видит — он захочет размер ее уменьшить. причем, как принято в windows — растягиванием. |
Юрий М Модератор Сообщений: 60581 Контакты см. в профиле |
|
Amberalex Пользователь Сообщений: 111 |
#11 27.10.2011 22:15:21 Есть многое на свете, что и не снилось нашим мудрецам… |