Vba excel форма на весь экран

Содержание

  1. Resize a UserForm with VBA or Windows API
  2. Windows API Solution
  3. How does it work?
  4. Setting up the Windows API code
  5. Setting up the UserForm
  6. VBA only solution
  7. How does it work?
  8. Setting up the UserForm
  9. Download the example file
  10. Vba excel форма на весь экран
  11. VBA Excel. Первая форма (для начинающих)
  12. Создание пользовательской формы
  13. Добавление элементов управления
  14. Отображение формы на экране

Resize a UserForm with VBA or Windows API

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.

  1. Change the Windows setting to enable the UserForm to be resized.
  2. On the UserForm use the Resize event to capture when the form is resized.
  3. 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).

This following code must be included within the same module as the code above but does not need to be directly below it.

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:

To turn off resizing, use the following

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.

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.

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

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.

  1. The UserForm contains an object which when clicked records the position of the mouse.
  2. As the mouse moves, the UserForm and it’s objects are repositioned or resized based on the new mouse position.
  3. 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.

When initializing the UserForm, the code below will place the lblResizer into the bottom right corner, and set the minimum permitted window size.

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.

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.

The following code triggers when the mouse button is released; the mouse movement ceases to resize the UserForm.

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? Th e n 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:

Источник

Vba excel форма на весь экран

200?’200px’:»+(this.scrollHeight+5)+’px’);»>
Option Explicit
Public FormIsOn As Boolean
Public Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Public Declare Function GetSystemMetrics Lib «user32.dll» (ByVal nIndex As Long) As Long
Public Declare Function GetDesktopWindow Lib «user32» () As Long
Public Declare Function GetWindowRect Lib «user32» (ByVal hWnd As Long, lpRect As RECT) As Long

Public Function ScreenWidth() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenWidth = RRight ‘* Screen.TwipsPerPixelX
End Function

Public Function ScreenHeight() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenHeight = R.Bottom * Screen.TwipsPerPixelY
End Function

Sub test()
Dim x As Integer, y As Integer
x = GetSystemMetrics(0)
y = GetSystemMetrics(1)
MsgBox «Ширина экрана:» & x & » : » & y
End Sub

200?’200px’:»+(this.scrollHeight+5)+’px’);»>
Option Explicit
Public FormIsOn As Boolean
Public Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Public Declare Function GetSystemMetrics Lib «user32.dll» (ByVal nIndex As Long) As Long
Public Declare Function GetDesktopWindow Lib «user32» () As Long
Public Declare Function GetWindowRect Lib «user32» (ByVal hWnd As Long, lpRect As RECT) As Long

Public Function ScreenWidth() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenWidth = RRight ‘* Screen.TwipsPerPixelX
End Function

Public Function ScreenHeight() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenHeight = R.Bottom * Screen.TwipsPerPixelY
End Function

Sub test()
Dim x As Integer, y As Integer
x = GetSystemMetrics(0)
y = GetSystemMetrics(1)
MsgBox «Ширина экрана:» & x & » : » & y
End Sub

200?’200px’:»+(this.scrollHeight+5)+’px’);»>
Option Explicit
Public FormIsOn As Boolean
Public Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Public Declare Function GetSystemMetrics Lib «user32.dll» (ByVal nIndex As Long) As Long
Public Declare Function GetDesktopWindow Lib «user32» () As Long
Public Declare Function GetWindowRect Lib «user32» (ByVal hWnd As Long, lpRect As RECT) As Long

Public Function ScreenWidth() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenWidth = RRight ‘* Screen.TwipsPerPixelX
End Function

Public Function ScreenHeight() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenHeight = R.Bottom * Screen.TwipsPerPixelY
End Function

Sub test()
Dim x As Integer, y As Integer
x = GetSystemMetrics(0)
y = GetSystemMetrics(1)
MsgBox «Ширина экрана:» & x & » : » & y
End Sub

Источник

VBA Excel. Первая форма (для начинающих)

Пример создания пользовательской формы в редакторе VBA Excel для начинающих программировать с нуля. Добавление на форму текстового поля и кнопки.

Начинаем программировать с нуля
Часть 4. Первая форма
[Часть 1] [Часть 2] [Часть 3] [Часть 4]

Создание пользовательской формы

Создайте или откройте файл Excel с расширением .xlsm (Книга Excel с поддержкой макросов) или с расширением .xls в старых версиях приложения.

Перейдите в редактор VBA, нажав сочетание клавиш «Левая_клавиша_Alt+F11».

В открывшемся окне редактора VBA выберите вкладку «Insert» главного меню и нажмите кнопку «UserForm». То же подменю откроется при нажатии на вторую кнопку (после значка Excel) на панели инструментов.

На экране редактора VBA появится новая пользовательская форма с именем «UserForm1»:

Добавление элементов управления

Обычно вместе с пользовательской формой открывается панель инструментов «Toolbox», как на изображении выше, с набором элементов управления формы. Если панель инструментов «Toolbox» не отобразилась, ее можно вызвать, нажав кнопку «Toolbox» во вкладке «View»:

При наведении курсора на элементы управления появляются подсказки.

Найдите на панели инструментов «Toolbox» элемент управления с подсказкой «TextBox», кликните по нему и, затем, кликните в любом месте рабочего поля формы. Элемент управления «TextBox» (текстовое поле) будет добавлен на форму.

Найдите на панели инструментов «Toolbox» элемент управления с подсказкой «CommandButton», кликните по нему и, затем, кликните в любом месте рабочего поля формы. Элемент управления «CommandButton» (кнопка) будет добавлен на форму.

Кликнув по элементу управления на форме, вы можете изменять его размер, перетягивая границы за белые квадратики, и перетаскивать по форме, ухватив за одну из границ. Кликнув по заголовку формы или по ее рабочему полю, вы можете также изменять ее размер, перетягивая границы за белые квадратики.

Нажатием клавиши «F4» вызывается окно свойств, с помощью которого можно вручную задавать значения свойств пользовательской формы и элементов управления. В окне свойств отображаются свойства выбранного элемента управления или формы, если выбрана она. Также окно свойств можно вызвать, нажав кнопку «Properties Window» во вкладке «View».

Отображение формы на экране

Чтобы запустить пользовательскую форму для просмотра из редактора VBA, необходимо выбрать ее, кликнув по заголовку или свободному от элементов управления полю, и совершить одно из трех действий:

  • нажать клавишу «F5»;
  • нажать на треугольник на панели инструментов (на изображении выше треугольник находится под вкладкой «Debug»);
  • нажать кнопку «Run Sub/UserForm» во вкладке «Run».

Для запуска пользовательской формы с рабочего листа Excel, можно использовать кнопки, описанные в этой статье. Например, чтобы отобразить форму с помощью «кнопки – элемента ActiveX», используйте в модуле рабочего листа следующий код:

Источник

0 / 0 / 0

Регистрация: 17.03.2011

Сообщений: 9

1

Как сделать так, чтобы размер формы был максимальным т.е. форма была на весь экран?

17.03.2011, 11:24. Показов 7819. Ответов 6


Студворк — интернет-сервис помощи студентам

Привет. Помогите, пожалуйста, решить пару проблем. Есть Эксел файл, при открытии которого автоматически загружается пользовательская форма.
1) Как сделать так, чтобы размер формы был максимальным т.е. форма была на весь экран? Необходимо учесть, что приложение будет использоваться на машинах с различным разрешением дисплея.
2) Возможно ли сделать масштабирование объектов формы? Если да, то как?
Заранее спасибо,
Brudda



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

17.03.2011, 13:33

2

Могу подсказать как сделать форму эквивалентной размеру приложения (не экрана)



0



0 / 0 / 0

Регистрация: 17.03.2011

Сообщений: 9

17.03.2011, 13:47

 [ТС]

3

Сделай одолжение. Спасибо. Brudda



0



pashulka

4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

17.03.2011, 16:25

4

Обратите внимание на то, что за размер определяется исходя из приложения (в данном случае MS Excel)

Visual Basic
1
2
3
4
5
6
7
8
9
10
Private Sub UserForm_Initialize()
 
iAppWidth = Application.Width
iAppHeight = Application.Height
 
UserForm1.StartUpPosition = 0 ' Me.StartUpPosition = 0
UserForm1.Width = iAppWidth   ' Me.Width = iAppWidth
UserForm1.Height = iAppHeight ' Me.Height = iAppHeight
 
End Sub



0



Димит

90 / 37 / 14

Регистрация: 03.11.2010

Сообщений: 429

17.03.2011, 16:33

5

Разрешите добавить.

Visual Basic
1
2
3
4
5
6
7
Dim Z As Single
Z = Application.Height / Me.Height
If Application.Width / Me.Width < Z Then Z = Application.Width / Me.Width
If Z > 4 Then Z = 4
Me.Height = Me.Height * Z
Me.Width = Me.Width * Z
Me.Zoom = Z * 100

Так сохранятся соотнашение сторон формы и пропорционально изменятся элементы на форме



1



0 / 0 / 0

Регистрация: 17.03.2011

Сообщений: 9

17.03.2011, 16:44

 [ТС]

6

Спасибо.
Brudda.



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

17.03.2011, 18:15

7

Да… вопрос про Zoom я как-то и не заметил. Видать и вправду старею.

Примечание :
Если размер MSForm относительно приложения будут меньше чем в четыре раза, то новый размер формы не будет эквивалентен размеру приложения.

Однако вероятность подобного развития ситуации очень невелика.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

17.03.2011, 18:15

7

  • #1

Mr Excel,

I have created a userform in Visual Basic which automatically pops up when a workbook is opened. I would like it to appear in full screen mode ie self adjust to the users PC display settings / acceleration.

Is there a way to do this…if not I will have to design the form a little smaller to suit all needs (not the best solution but).

If you could help, I would be most appreciative.

Michael.

Can Excel fill bagel flavors?

You can teach Excel a new custom list. Type the list in cells, File, Options, Advanced, Edit Custom Lists, Import, OK

  • #2

Hi Michael,

Please try this code.
If you want to keep the ratio, zoom property makes it possible.

<pre>
Private Sub UserForm_Initialize()
With Application
.WindowState = xlMaximized
Zoom = Int(.Width / Me.Width * 100)
Width = .Width
Height = .Height
End With
End Sub
</pre>

  • #3

Thanks Colo for answering Michael’s question! I needed to do this with my project too!

  • #4

Thank you Sir Colo for the solution. I need the same for my small project.
God bless you.

  • #5

Hello Colo

Handy code, thanks.

ColdGeorge

  • #6

for some reason i get the error runtime 380, could not set the zoom property please enter a value between 10 and 400?

  • #7

Your userform is too small compared to the size of your screen. Make it bigger if you want to use this method.

Установка состояния окна приложения Excel из кода VBA с помощью свойства Application.WindowState. Сворачивание и разворачивание окна. Чтение данных о состоянии окна.

Application.WindowState — это свойство, которое задает или возвращает состояние окна приложения Excel.

Состояние окна приложения Excel задается константой из коллекции XlWindowState, при чтении информации о состоянии окна — свойство Application.WindowState возвращает числовое значение константы.

Свойство Application.WindowState позволяет развернуть окно приложения Excel из кода VBA на весь экран — до максимального размера, свернуть окно «в иконку» или задать ему нормальные размеры, установленные ранее, развернув из свернутого или свернув из максимального.

Синтаксис свойства WindowState объекта Application:

Константы XlWindowState

Константы из коллекции XlWindowState:

Константа Значение Описание
xlMaximized -4137 Максимальное окно (развернуто на весь экран)
xlMinimized -4140 Минимальное окно (свернуто «в иконку»)
xlNormal -4143 Нормальное окно (размеры, установленные ранее)

Пример кода с WindowState

Пример записи и чтения свойства Application.WindowState:

Sub Test()

‘Запись свойства WindowState

Application.WindowState = xlMaximized  ‘или -4137

‘Application.WindowState = xlMinimized  ‘или -4140

‘Application.WindowState = xlNormal  ‘или -4143

‘Проверка, в каком состоянии находится окно приложения

MsgBox Application.WindowState

End Sub

Попробуйте по очереди задавать разные константы свойству Application.WindowState и смотрите, какое значение будет считано. У меня получились удивительные результаты при выполнении строк кода по очереди, как в примере:

  • Application.WindowState = xlMinimized — MsgBox возвращает совсем не -4140;
  • после первого запуска Application.WindowState = xlNormal — окно приложения разворачивается на весь экран, после второго запуска — переходит к нормальному состоянию.

Не удалось мне добиться значения -4140 и при минимизации окна вручную, разместив предварительно следующий код в модуль книги:

Private Sub Workbook_WindowResize(ByVal Wn As Window)

    MsgBox Application.WindowState

End Sub


Brudda
Обычный пользователь
Обычный пользователь
 
Сообщения: 79
Зарегистрирован: 21.02.2005 (Пн) 14:47
Откуда: Рига

Как сделать форму (UserForm) на весь экран?

Добрый день.
Мне кажется, что что-то похожее уже обсуждалось, но найти мне не удалось. Задача: необходимо сделать так, что бы сразу же после открытия файла на экране открывалась форма (UserForm) и ее размер был максимальным (на весь экран) для данной системы (т.е. монитор — разрешение и что там еще может быть). Может подскажете чего путного?
Заранее спасибо.
С почтением,
Brudda


Brudda
Обычный пользователь
Обычный пользователь
 
Сообщения: 79
Зарегистрирован: 21.02.2005 (Пн) 14:47
Откуда: Рига

Re: Как сделать форму (UserForm) на весь экран?

Сообщение Brudda » 06.09.2008 (Сб) 13:53

Покапался я в инете и вот что нашел:

Код: Выделить всё
Me.Height = Application.UsableHeight
Me.Width = Application.UsableWidth

Работает.

Читающим по-английски: похоже неплохой форум здесь http://www.mrexcel.com/forum/index.php
Brudda


KL
Microsoft MVP
 
Сообщения: 483
Зарегистрирован: 30.10.2005 (Вс) 0:31
Откуда: Madrid

Re: Как сделать форму (UserForm) на весь экран?

Сообщение KL » 06.09.2008 (Сб) 18:30

см. пример в приложении

Вложения
Book1.xls
(45 Кб) Скачиваний: 377

Последний раз редактировалось KL 07.09.2008 (Вс) 14:06, всего редактировалось 1 раз.

Привет,

KL



Вернуться в VBA

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 1

Понравилась статья? Поделить с друзьями:
  • Vba excel форма картинки
  • Vba excel условие для диапазона
  • Vba excel удалить подстроку
  • Vba excel форма для всех книг
  • Vba excel условие в условии