Элемент управления пользовательской формы ScrollBar, применяемый в VBA Excel для создания полосы прокрутки. Свойства UserForm.ScrollBar, примеры кода.
UserForm.ScrollBar – это элемент управления пользовательской формы, представляющий из себя полосу прокрутки с кнопками, реагирующий как на перемещение ползунка, так и на нажатие кнопок.
Элемент управления ScrollBar предназначен в VBA Excel для ввода пользователем числовых данных, которые ограничены минимальным и максимальным значениями. Увеличение или уменьшение значения полосы прокрутки осуществляется с указанным шагом при помощи ползунка или кнопок.
Визуально, элемент управления ScrollBar состоит из полосы прокрутки и двух кнопок, работающих аналогично кнопкам элемента управления SpinButton. Ориентация может быть горизонтальной или вертикальной в зависимости от настроек.
Полоса прокрутки в VBA Excel используется в паре с элементом управления TextBox или Label. Вспомогательный элемент необходим, чтобы отобразить текущее значение ScrollBar на пользовательской форме.
Свойства элемента ScrollBar
Свойство | Описание |
---|---|
BackColor | Цветовое оформление элемента управления. |
Delay* | Время между последовательными событиями при удержании кнопки. |
ControlTipText | Текст всплывающей подсказки при наведении курсора на полосу прокрутки. |
Enabled | Возможность взаимодействия пользователя с элементом управления. True – взаимодействие включено, False – отключено (цвет стрелок становится серым). |
Height | Высота элемента управления. |
Left | Расстояние от левого края внутренней границы пользовательской формы до левого края элемента управления. |
Max | Максимальное значение свойства Value. |
Min | Минимальное значение свойства Value. |
Orientation** | Задает горизонтальную или вертикальную ориентацию элемента управления ScrollBar. |
SmallChange | Шаг изменения значения свойства Value. |
TabIndex | Определяет позицию элемента управления в очереди на получение фокуса при табуляции, вызываемой нажатием клавиш «Tab», «Enter». Отсчет начинается с 0. |
Top | Расстояние от верхнего края внутренней границы пользовательской формы до верхнего края элемента управления. |
Visible | Видимость элемента ScrollBar. True – элемент отображается на пользовательской форме, False – скрыт. |
Width | Ширина элемента управления. |
* По умолчанию свойство Delay равно 50 миллисекундам. Это означает, что первое событие (SpinUp, SpinDown, Change) происходит через 250 миллисекунд после нажатия кнопки, а каждое последующее событие – через каждые 50 миллисекунд (и так до отпускания кнопки).
** По умолчанию включена автоматическая ориентация, которая зависит от соотношения между шириной и высотой элемента управления. Если ширина больше высоты – ориентация горизонтальная, если высота больше ширины – ориентация вертикальная.
В таблице перечислены только основные, часто используемые свойства полосы прокрутки. Все доступные свойства отображены в окне Properties элемента управления ScrollBar.
Примеры кода с полосой прокрутки
Пример 1
Условие примера 1
- На пользовательской форме VBA Excel расположены элементы управления ScrollBar1 и Label1.
- Необходимо задать для полосы прокрутки ScrollBar1 интервал значений от -100 до 100 единиц с шагом 5 и отображением текущего значения на элементе Label1.
- При открытии формы полоса прокрутки должна быть установлена на значении 0.
Решение примера 1
Первоначальные настройки при открытии пользовательской формы:
Private Sub UserForm_Initialize() Me.Caption = «Пример 1» With ScrollBar1 .Min = —100 .Max = 100 .SmallChange = 5 .Value = 0 End With Label1.Caption = «0» End Sub |
Обработка события Change объекта ScrollBar1:
Private Sub ScrollBar1_Change() Label1.Caption = ScrollBar1.Value End Sub |
Обе процедуры размещаются в модуле пользовательской формы VBA Excel.
Пример 2
Условие примера 2
- На пользовательской форме расположены элементы управления ScrollBar1 и TextBox1.
- Интервал значений для полосы прокрутки ScrollBar1 от 0 до 1000 единиц с шагом 10 и отображение текущего значения в поле элемента TextBox1.
- При открытии формы полоса прокрутки должна быть установлена в значение 0.
- Установка соответствующего значения полосы прокрутки при ручном изменении содержимого текстового поля.
- Предусмотреть сообщение о значении TextBox1, не входящем в интервал значений элемента управления ScrollBar1.
Решение примера 2
Первоначальные настройки при открытии пользовательской формы:
Private Sub UserForm_Initialize() Me.Caption = «Пример 2» With ScrollBar1 .Min = 0 .Max = 1000 .SmallChange = 10 .Value = 0 End With TextBox1.Text = «0» End Sub |
Обработка события Change объекта ScrollBar1:
Private Sub ScrollBar1_Change() TextBox1.Text = ScrollBar1.Value End Sub |
Обработка события Change объекта TextBox1:
Private Sub TextBox1_Change() On Error GoTo Instr ScrollBar1.Value = TextBox1.Text Exit Sub Instr: TextBox1.Text = «Недопустимое значение» End Sub |
Если содержимое элемента управления TextBox1 не соответствует интервалу значений полосы прокрутки, возникает ошибка (преобразование в число происходит автоматически). Чтобы ее избежать и вывести сообщение о недопустимости значения, используется обработчик ошибок.
Все три процедуры размещаются в модуле пользовательской формы.
How to make a scrollable UserForm. This allows you to put scroll bars onto a form so that it can hold information that is accesible when the user scrolls down or to the right.
Sections:
Make a Scrollable UserForm
Notes
Make a Scrollable UserForm
Make sure you are viewing the form. Alt+F11 to go to the VBA window > Double-click the UserForm from the Project window (Ctrl+R if you don’t see that window) and then make sure the form itself is selected and not a control within the form; do this by clicking the title bar at the top of the form.
Also, make sure the properties window is displayed, if it isn’t, hit F4 to display it.
- For now, make the form large enough to display all of the contents on it; then, look to the properties window and take note of the number for the Height property:
The value of 236.25 is what is needed to display everything on the form and this number will be used later in the tutorial.
If your form is very wide and you need a scroll bar to go left-to-right, also look to the Width property and take note of that number when the form is large enough to display everything. - Go down to the ScrollBars option.
Click the option to the right so that a menu appears.
Choose the correct option:
fmScrollBarsHorizontal means that left-to-right scroll bars will appear.
fmScrollBarsVertical means that up-and-down scroll bars will appear — most common choice.
fmScrollBarsBoth means that both horizontal and vertical scroll bars will appear. - Take the number that you got from Step 1 and put that into the ScrollHeight property if you are using vertical scroll bars and/or if you are using horizontal scroll bars, put the value from the Width property in for the ScrollWidth property.
In this example we will only use vertical scroll bars.
You will also notice that once you enter the number for the ScrollHeight or ScrollWidth property, the scroll bar will appear on the form, as you can see in the image above. - Make sure that the values for ScrollLeft and ScrollTop are set to 0. These properties allow you to have a form that is part of the way scrolled by default; if that sounds confusing, just wait until you get the scroll bars working and test some values for this field, say 20, and then run the form and you will understand.
- Resize the form so that it is the size that you want it to be, which should be smaller than it was in step 1. Once you do this, you will see that some of the controls will no longer be visible.
You are now ready to test the form out!
Run the form to see the results:
If you notice too much empty space at the bottom of the form, just go back to the property window and adjust the value for the ScrollHeight property until it looks right to you — do the same for the width if you are using horizontal scroll bars.
Notes
Adding scroll bars to UserForms is not difficult, it’s just a little bit annoying since it doesn’t work as intuitively as it seems like it should.
Just remember, to adjust these properties:
- ScrollBars
- ScrollHeight and/or ScrollWidth
- ScrollLeft and/or ScrollTop
The ScrollLeft and ScrollTop properties are rarely used because, usually, forms start at the upper-left-most position.
Make sure to download the sample file for this tutorial so you can see this example in Excel.
Excel VBA Course — From Beginner to Expert
200+ Video Lessons
50+ Hours of Instruction
200+ Excel Guides
Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)
View Course
Similar Content on TeachExcel
Make Perfect Scrollable Boxes in Worksheets in Excel — Great for a Dashboard
Tutorial:
Make a scrollable box in a worksheet in Excel that allows you to scroll through a table o…
Make a UserForm in Excel
Tutorial: Let’s create a working UserForm in Excel.
This is a step-by-step tutorial that shows you e…
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…
Use Macros with UserForms
Tutorial: This tutorial explains how macros interact with UserForms.
This includes an explanation of…
Showing a UserForm
Tutorial: How to display a UserForm in Excel and some common things you might want to do when you di…
Subscribe for Weekly Tutorials
BONUS: subscribe now to download our Top Tutorials Ebook!
Excel VBA Course — From Beginner to Expert
200+ Video Lessons
50+ Hours of Video
200+ Excel Guides
Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)
View Course
Diana
Пользователь
Сообщений: 982
Регистрация: 28.12.2012
#6
14.09.2012 21:59:12
ABC, если MultiPages имеете ввиду, то пробовала, конечно, их там и так предостаточно. Вопрос стоит именно в том, чтобы организовать или прокрутку или (не знаю, как точно это называется на русском… когда размер рабочего стола windows больше, чем размер экрана, мышкой водим — экран перемещается). Как то так
UserForm Controls — ScrollBar and SpinButton
UserForm acts as a container in which you add multiple ActiveX controls, each of which has a specific use and associated properties. By itself, a UserForm will not be of much use unless ActiveX controls are added to it which are the actual user-interactive objects. Using ActiveX Controls on a Worksheet have been illustrated in detail, in the separate section of «Excel VBA: ActiveX Controls, Form Controls & AutoShapes on a Worksheet».
Also refer «2. UserForm and Controls — Properties» for properties common to the UserForm and most Controls
Note: In below given examples, vba codes are required to be entered in the Code Module of the UserForm, unless specified otherwise.
——————————————-
Contents:
ScrollBar Control
SpinButton Control
——————————————-
ScrollBar Control
A ScrollBar control enables to change (increment or decrement) the value displayed by other UserForm controls (viz. TextBox, Label, …) or the value in a worksheet range. It scrolls through a range of values when a user: (i) clicks on the scroll arrows; (ii) drags the scroll box; or (iii) clicks in an area between a scroll arrow and the scroll box. ScrollBar & SpinButton controls — the difference between the two is that the ScrollBar box can be dragged to change the control’s value over larger increments (while keeping the increment low for clicks) which advantages a ScrollBar to make a selection from across a large number of values and cover an extremely wide range.
SmallChange Property specifies the incremental change, as an integer value (Long variable), that occurs when a user clicks the scroll arrow. The LargeChange Property specifies the incremental change when the user clicks between a scroll arrow and the scroll box. The default value is 1 for both the properties.
Min and Max Properties are integer values (Long variable) which specify the minimum and maximum acceptable values of the ScrollBar control (for the Value property setting). In a vertical ScrollBar clicking down the scroll arrow increases the value and the lowest position displays the maximum value (will be reverse when you click up the scroll arrow). In a horizontal ScrollBar clicking the right scroll arrow increases the value and the rightmost position displays the maximum value (will be reverse when you click the left scroll arrow).
Orientation Property determines a vertical ScrollBar or a horizontal ScrollBar. It has 3 settings: (i) fmOrientationAuto (Value -1) — this is the default value wherein the ScrollBar dimensions automatically determine whether the ScrollBar is Vertical or Horizontal. Where width is more than height, ScrollBar is Horizontal and where height is more than width, ScrollBar is Vertical; (ii) FmOrientationVertical (Value 0) — vertical ScrollBar; and (iii) FmOrientationHorizontal (Value 1) — horizontal ScrollBar.
Example 1: Creating a Mortgage Calculator, using ScrollBar controls. Refer Image 29. See vba codes below:
Private Sub UserForm_Initialize()
‘Set properties of Controls on initialization of UserForm.
‘set properties for controls in re of Loan Amount:
TextBox1.BackColor = RGB(255, 255, 0)
TextBox1.TextAlign = fmTextAlignCenter
TextBox1.Font.Bold = True
TextBox1.Enabled = False
Label1.Caption = «Loan Amount ($):»
Label1.TextAlign = fmTextAlignLeft
ScrollBar1.Min = 0
ScrollBar1.Max = 10000
ScrollBar1.Orientation = fmOrientationHorizontal
ScrollBar1.SmallChange = 5
ScrollBar1.LargeChange = 100
ScrollBar1.Value = 0
‘set properties for controls in re of Annual Interest Rate:
TextBox2.BackColor = RGB(255, 255, 0)
TextBox2.TextAlign = fmTextAlignCenter
TextBox2.Font.Bold = True
TextBox2.Enabled = False
Label2.Caption = «Annual Int Rate (%):»
Label2.TextAlign = fmTextAlignLeft
ScrollBar2.Min = 0
ScrollBar2.Max = 1000
ScrollBar2.Orientation = fmOrientationHorizontal
ScrollBar2.SmallChange = 1
ScrollBar2.LargeChange = 10
ScrollBar2.Value = 0
‘set properties for controls in re of Loan Tenure:
TextBox3.BackColor = RGB(255, 255, 0)
TextBox3.TextAlign = fmTextAlignCenter
TextBox3.Font.Bold = True
TextBox3.Enabled = False
Label3.Caption = «Loan Tenure (Yrs)»
Label3.TextAlign = fmTextAlignLeft
ScrollBar3.Min = 0
ScrollBar3.Max = 50
ScrollBar3.Orientation = fmOrientationHorizontal
ScrollBar3.SmallChange = 1
ScrollBar3.LargeChange = 4
ScrollBar3.Value = 0
‘set properties for Label which displays Monthly Instalment:
Label4.Caption = «Monthly Instalment: $»
Label4.TextAlign = fmTextAlignCenter
Label4.BackColor = RGB(0, 255, 0)
Label4.Font.Bold = True
End Sub
Private Sub ScrollBar1_Change()
‘in re of Loan Amount, clicking the scroll arrow will increment amount by $5,000 and clicking between a scroll arrow and the scroll box will increment amount by $100,000:
TextBox1.Value = ScrollBar1.Value * 1000
TextBox1.Value = «$» & Format(TextBox1.Value, «#,##0»)
End Sub
Private Sub ScrollBar2_Change()
‘in re of Annual Interest Rate, clicking the scroll arrow will increment rate by 0.1% and clicking between a scroll arrow and the scroll box will increment rate by 1%:
TextBox2.Value = ScrollBar2.Value / 10
End Sub
Private Sub ScrollBar3_Change()
‘in re of Loan Tenure, clicking the scroll arrow will increment year by 0.5 and clicking between a scroll arrow and the scroll box will increment year by 2:
TextBox3.Value = ScrollBar3.Value / 2
End Sub
Private Sub CommandButton1_Click()
‘calculates the Monthly Instalment using the excel PMT function:
Dim mi As Currency
If Not TextBox1.Value > 0 Then
MsgBox «Please Enter Loan Amount!»
Exit Sub
ElseIf Not TextBox2.Value > 0 Then
MsgBox «Please Enter Annual Interest Rate!»
Exit Sub
ElseIf Not TextBox3.Value > 0 Then
MsgBox «Please Enter Loan Tenure!»
Exit Sub
Else
mi = Pmt((TextBox2.Value / 100) / 12, TextBox3.Value * 12, TextBox1.Value)
‘Label displays the monthly instalment, rounded off to 2 decimal points:
Label4.Caption = «Monthly Instalment: $» & Round(mi, 2) * -1
End If
End Sub
Private Sub CommandButton2_Click()
‘close button unloads the UserForm
Unload Me
End Sub
————————————————————————————————————-
SpinButton Control
A SpinButton control, similar to a ScrollBar control, is used to increment or decrement the value (viz. a number, date, time, etc.) displayed by other UserForm controls (viz. TextBox, Label, …) or the value in a worksheet range. A SpinButton control (also referred to as a Spinner control) functions like a ScrollBar control, with similar properties (viz. SmallChange, Min, Max, Orientation, …). SmallChange Property specifies the incremental change, as an integer value (Long variable), that occurs when a user clicks the scroll arrow. A SpinButton control does not have a LargeChange property, like in a ScrollBar. In a vertical ScrollBar clicking up the scroll arrow decreases the value whereas clicking up the scroll arrow on a vertical Spinner increases the value.
ScrollBar & SpinButton controls — the difference between the two is that the ScrollBar box can be dragged to change the control’s value over larger increments (while keeping the increment low for clicks) which advantages a ScrollBar to make a selection from across a large number of values and cover an extremely wide range.
Example 2: Using a SpinButton control to change dates in TextBox, within a specified range:
Private Sub UserForm_Initialize()
‘populate a date in the TextBox
Dim dt As Date
‘disallow manual input in TextBox
TextBox1.Enabled = False
dt = «09/15/2011»
TextBox1.Text = dt
End Sub
Private Sub SpinButton1_SpinUp()
‘increase date by one day at a time, within the same month:
Dim dtUpper As Date
dtUpper = «09/30/2011»
If DateValue(TextBox1.Text) < dtUpper Then
TextBox1.Text = DateValue(TextBox1.Text) + 1
End If
End Sub
Private Sub SpinButton1_SpinDown()
‘decrease date by one day at a time, within the same month:
Dim dtLower As Date
If DateValue(TextBox1.Text) > dtLower Then
TextBox1.Text = DateValue(TextBox1.Text) — 1
End If
End Sub
Example 3: Move ListBox Items Up/Down in the list order and in the worksheet range, using the SpinButton control (by clicking Up or Down the scroll arrow). Refer Image 30. See below vba codes:
Private Sub loadListBox()
‘load ListBox from worksheet range:
Dim n As Integer
Dim cell As Range
Dim rng As Range
Set rng = Sheet7.Range(«A1:A6»)
For n = 1 To ListBox1.ListCount
ListBox1.RemoveItem ListBox1.ListCount — 1
Next n
For Each cell In rng.Cells
Me.ListBox1.AddItem cell.Value
Next cell
End Sub
Private Sub UserForm_Initialize()
‘loads ListBox on initializing of UserForm
loadListBox
End Sub
Private Sub SpinButton1_SpinUp()
‘clicking up the scroll arrow moves the selected ListBox item one up both in the list order and also in the linked worksheet range:
Dim n As Long
n = ListBox1.ListIndex
If n > 0 Then
Sheet7.Range(«A» & n + 1).Value = Sheet7.Range(«A» & n).Value
Sheet7.Range(«A» & n).Value = ListBox1.Value
loadListBox
ListBox1.Selected(n — 1) = True
ElseIf ListBox1.ListIndex = 0 Then
MsgBox «First Item cannot be moved Up!»
Else
MsgBox «Please select item!»
End If
End Sub
Private Sub SpinButton1_SpinDown()
‘clicking down the scroll arrow moves the selected ListBox item one down both in the list order and also in the linked worksheet range:
Dim n As Long
n = ListBox1.ListIndex
If n >= 0 And n < ListBox1.ListCount — 1 Then
Sheet7.Range(«A» & n + 1).Value = Sheet7.Range(«A» & n + 2).Value
Sheet7.Range(«A» & n + 2).Value = ListBox1.Value
loadListBox
ListBox1.Selected(n + 1) = True
ElseIf ListBox1.ListIndex = ListBox1.ListCount — 1 Then
MsgBox «Last Item cannot be moved Down!»
Else
MsgBox «Please select item!»
End If
End Sub
Private Sub CommandButton1_Click()
‘clicking the Close button unloads the UserForm
Unload Me
End Sub
Some times we need to use very large userforms in our VBA projects. Size of the form depends on the number of fields and various objects we have in our form. And if we need to show them in one window, we need to create big userform to put them all. You can create a form of any size by giving appropriate values for Height and width in properties window. But if our userform is bigger than the screen we need to use scroll bars inside our form. It is easier to put a scroll bar to a userform. But I saw that many people have problems with setting scroll bars correctly. Lot of people say that their scroll bars not working at run time. So there are few important things you should know when using scroll bars.
I will explain these important facts using a simple example. I have created a large form which has height of 1200 and width of 420. And there are a lot of text fields inside my userform.
If you look at properties window, you will notice that ScrollBars value is set to 0-fmScrollBarsNone by default. So we need to change this property depending on our requirement. If you have a userform with larger width, then you need to set ScrollBars value to 1-fmScrollBarsHorizontal. If you have a userform which has higher height, then you need to set this value to 2-fmScrollBarsVertical. And if you need scroll bars in both directions you can set the value to 3-fmScrollBarsBoth. You need to set to this value only if both width and height of your form is bigger than the screen.
You should set ScrollTop value to the 0. So then it will always appear at top.
Finally you need to set the ScrollHeight. It is very important to set appropriate value to this. Othewise you may not able to scroll up to the bottom of the form. Also if you set higher value, then user will scroll after the end of the objects. So user will see like your form is extended more than needed. So you should set a optimum value for this property for correct functionality and nice appearance. For example if you have a form having a height of 1200, you should set ScrollHeight value around 1850.
Элемент управления ScrollBar представляет из себя всем знакомую полосу прокрутки, которая встречается в текстовых полях, когда их содержимое не умещается на поверхности. Только в данном случае, его логика работы немного меняется.
VBA Объект ScrollBar удобно использовать, когда нужно увеличить или уменьшить диапазон. Так, можно с его помощью задавать диапазон для вычисления суммы чисел, или, в зависимости от положения ползунка менять цвет текста. Понятно, что в этом случае удобно использовать цикл for. Примером использования объекта ScrollBar VBA может служить регулятор громкости, контраста и так далее.
Базовые свойства класса ScrollBar VBA
Max и Min – данные свойства позволяют задать максимальное и минимальное значение, которые вы сможете определить используя данные элемент управления. Свойство принимает только целые значения в диапазоне от −32 767 до +32 767. Вы можете задавать значения как в прямом порядке (от меньшего к большего) так и в обратном (от большего к меньшему). В таких случаях ползунок нужно будет тянуть в том или ином направлении.
SmallChange – свойство vba принимает целое значение, которое определяет, на какую величину будет перемещаться ползунок при нажатии на кнопки прокрутки.
LargeChange – как и свойство SmallChange позволяет задать шаг перемещения ползунка при нажатии на полосу прокрутки. Значения могут быть в диапазоне от −32 767 до +32 767, по умолчанию значения равны для обоих свойств 1.
Orientation – свойство позволяет указать ориентацию ползунка – горизонтальную или вертикальную. По умолчанию значение ровно 1 – ориентация определяется автоматически исходя из параметров формы, то есть, как полоса прокрутки умещается на объекте UserForm. Можно и явно указать ориентацию объекта ScrollBar, -1 – горизонтальная ориентация и 0 – вертикальная.
Visible – собственно, определяет видимость vba компонента ScrollBar, значение true установлено по умолчанию – объект видим, и false – скрываем элемент управления от глаз пользователя.
Value – позволяет получить значение ползунка, в зависимости от его положения.
Как и большинства элементов управления, основным событием для ScrollBar VBA является событие Change, которое возникает при перемещении ползунка.
Теперь настало время приступить к практике
Откройте редактор Visual Basic (Alt + F11), и в окно редактора Проектов добавьте новую форму и модуль, я назвал форму ScrollForm и модуль ScrollModule, за имя отвечает свойство Name. В редакторе кода для модуля пропишите код:
Sub ScrollModule() ScrollForm.Show End Sub
Тут мы определяем, что при запуске модуля (макроса) с именем ScrollModule надо показать форму с именем ScrollForm, свойство Show делает объекта класса UserForm видимым.
Теперь на поверхности формы нам нужно расположить следующие элементы управления:
Label1 – метка, в которой пропишем текст “Полоса прокрутки”
ScrollBar1 – полоса прокрутки, которая размещается под меткой, она должна быть горизонтальной. С ее помощью мы будет задавать диапазон значений от 1 до 100, и потом будем вычислять сумму заданных чисел.
Label2 – вторая метка, удалите в ней весь текст, в ней мы будет отображать результат суммирования.
Теперь в редакторе кода для формы пропишем следующие процедуры:
Private Sub ScrollBar1_Change() Dim summ summ = 1 ' вычисляем сумму чисел For i = 1 To ScrollBar1.Value summ = summ + i Next Label2.Caption = "Сумма чисел от 1 до " & ScrollBar1.Value & " ровна: " & summ End Sub Private Sub UserForm_Initialize() Dim summ summ = 1 ' вычесляем сумму чисел For i = 1 To ScrollBar1.Value summ = summ + i Next ' параметры первого текстового поля Label1.FontSize = 15 Label1.ForeColor = &HCD Label1.TextAlign = fmTextAlignCenter ' параметры полосы прокрутки ScrollBar1.Min = 1 ScrollBar1.Max = 100 ' параметры второго текстового поля Label2.FontSize = 15 Label2.ForeColor = &HFF0000 Label2.TextAlign = fmTextAlignCenter Label2.Caption = "Сумма чисел от 1 до " & ScrollBar1.Value & " ровна: " & summ End Sub
ScrollBar1_Change – тут происходит обработка события Change. В цикле происходит суммирование чисел от 1 до ScrollBar1.Value. Тут ScrollBar1.Value содержит выбранное значение на полосе прокрутки, результат суммирования будет хранить переменная summ. Также в свойство Caption объекта Label2 записывается результат суммирования.
UserForm_Initialize – тут происходит определение начальных свойств при инициализации формы. Размер и текст меток, задается минимальное (один) и максимальное (сто) значение для полос прокрутки. Тут также используется цикл для суммирования значений.
И так, давайте просуммируем: мы рассмотрели пример использования объекта класса ScrollBar VBA языка, который позволяет добавлять на поверхность формы UserForm полосу прокрутки.
VBA UserForm MouseScroll
MouseScroll is a VBA Project that allows Mouse Wheel Scrolling on MSForms Controls and Userforms but can also be extended for clicks, double-clicks and movement inputs.
Multiple forms are tracked simultaneously. Just call the EnableMouseScroll
for each form.
Installation
Just import the following 2 code modules in your VBA Project:
- MouseScroll.bas
- MouseOverControl.cls
Usage
In your Modal Userform use:
EnableMouseScroll myUserForm
For example you can use your Form’s Initialize Event:
Private Sub UserForm_Initialize() Me.StartUpPosition = 0 Me.Left = Application.Left + Application.Width / 2 - Me.Width / 2 Me.Top = Application.Top + Application.Height / 2 - Me.Height / 2 EnableMouseScroll Me End Sub
Not needed, but the following code can be added in the Form’s Terminate Event for extra safety:
Private Sub UserForm_Terminate() DisableMouseScroll Me End Sub
Notes
- Hold Shift for Horizontal Scroll and Ctrl for Zoom
- The Mouse Hook will not work with Modeless Forms (Modal only)
- No need to call the
DisableMouseScroll
method. It will be called automatically (from the MouseScroll.bas module) when the Form’s Window is destroyed - Multiple forms are now tracked simultaneously and the mouse is unhooked automatically only when no forms are being tracked
- You can download the available Demo Workbook for a quick start
Other Controls
ListView
,TreeView
control- Requires a reference to Microsoft Windows Common Controls
- The value of the compiler constant
DETECT_COMMON_CONTROLS
(inside MouseOverControl.cls) needs to be set to a value of 1
WebBrowser
control- Requires a reference to Microsoft Internet Controls for the main control
- Requires a reference to Microsoft HTML Object Library for the HTMLDocument control that tracks the
onmousemove
event - The value of the compiler constant
DETECT_INTERNT_CONTROLS
(inside MouseOverControl.cls) needs to be set to a value of 1
License
MIT License
Copyright (c) 2019 Ion Cristian Buse
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Workbook demo
The following generic code enables MouseWheel scrolling for UserForms and Frames … You just need to pass the UserForm or the Frame to the SetScrollHook routine in the UserForm_Activate event as follows :
Code:
Private Sub UserForm_Activate()
[COLOR=#008000]'Call SetScrollHook(Me) '.. Apply the mousewheel scrolling to the Userform[/COLOR]
Call SetScrollHook(Me.Frame1) [COLOR=#008000]'.. Apply the mousewheel scrolling to the Frame[/COLOR]
End Sub
You can’t apply the mousewheel functionality to more than one object simultaniously (I’ll try to modify the code later to make it work with the userform and with different frames within the form simultaniously)
In order to scroll the frame
horizontally
, have the Ctl key held down
Proceedings:
1- Create a new UserForm (UserForm1) and add a frame to it (Frame1)
2- Place this code in the UserForm Module :
Code:
Private Sub UserForm_Activate()
'Call SetScrollHook(Me) '.. Apply the mousewheel scrolling to the Userform
Call SetScrollHook(Me.Frame1) '.. Apply the mousewheel scrolling to the Frame
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
RemoveScrollHook
End Sub
3- Add a Standard Module to the project and place the following code in it:
Code:
Option Explicit
Private Type POINTAPI
X As Long
Y As Long
End Type
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Type MOUSEHOOKSTRUCT
pt As POINTAPI
hwnd As Long
wHitTestCode As Long
dwExtraInfo As Long
End Type
Private Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As Long, ByVal hmod As Long, ByVal dwThreadId As Long) As Long
Private Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, ByVal nCode As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
Private Declare Function GetDeviceCaps Lib "gdi32" (ByVal hdc As Long, ByVal nIndex As Long) As Long
Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hdc As Long) As Long
Private Declare Function PtInRect Lib "user32" (lpRect As RECT, ByVal X As Long, ByVal Y As Long) As Long
Private Declare Function ClientToScreen Lib "user32" (ByVal hwnd As Long, lpPoint As POINTAPI) As Long
Private Declare Function GetClientRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long
Private Declare Function GetActiveWindow Lib "user32" () As Long
Private Declare Function SetRect Lib "user32" (lpRect As RECT, ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
Private Const WH_MOUSE_LL As Long = 14
Private Const WM_MOUSEWHEEL As Long = &H20A
Private Const HC_ACTION As Long = 0
Private Const POINTSPERINCH As Long = 72
Private Const LOGPIXELSX As Long = 88
Private Const LOGPIXELSY As Long = 90
Private Const SCROLL_CHANGE As Long = 5
Private lMouseHook As Long
Private lFormHwnd As Long
Private bHookIsSet As Boolean
Private oScrollableObject As Object
Public Sub SetScrollHook(ByVal ScrollableObject As Object)
If Not (IsObjectUserForm(ScrollableObject) Or TypeName(ScrollableObject) = "Frame") Then Exit Sub
Set oScrollableObject = ScrollableObject
lFormHwnd = GetActiveWindow
With ScrollableObject
.ScrollBars = fmScrollBarsBoth
.KeepScrollBarsVisible = fmScrollBarsBoth
.PictureAlignment = fmPictureAlignmentTopLeft
' Adjust the values of the scroll width and height properties as required
.ScrollWidth = ScrollableObject.InsideWidth * 3
.ScrollHeight = ScrollableObject.InsideHeight * 2
End With
If Not bHookIsSet Then
lMouseHook = SetWindowsHookEx( _
WH_MOUSE_LL, AddressOf MouseProc, Application.Hinstance, 0)
bHookIsSet = lMouseHook <> 0
End If
End Sub
Public Sub RemoveScrollHook(Optional ByVal Dummy As Boolean)
If bHookIsSet Then
UnhookWindowsHookEx lMouseHook
lMouseHook = 0
bHookIsSet = False
End If
End Sub
Private Function MouseProc(ByVal nCode As Long, ByVal wParam As Long, ByRef lParam As MOUSEHOOKSTRUCT) As Long
Dim tTopLeft As POINTAPI
Dim tBottomRight As POINTAPI
Dim tRect As RECT
GetClientRect lFormHwnd, tRect
With oScrollableObject
If IsObjectUserForm(oScrollableObject) Then
tTopLeft.X = tRect.Left
tTopLeft.Y = tRect.Top
tBottomRight.X = tRect.Right
tBottomRight.Y = tRect.Bottom
Else
tTopLeft.X = PTtoPX(.Left, False) + tRect.Left
tTopLeft.Y = PTtoPX(.Top, True) + tRect.Top
tBottomRight.X = PTtoPX(.Left + .Width, False) + tRect.Left
tBottomRight.Y = PTtoPX(.Top + .Height, True) + tRect.Top
End If
End With
ClientToScreen lFormHwnd, tTopLeft
ClientToScreen lFormHwnd, tBottomRight
SetRect tRect, tTopLeft.X, tTopLeft.Y, tBottomRight.X, tBottomRight.Y
On Error GoTo errH
If (nCode = HC_ACTION) And CBool(PtInRect(tRect, lParam.pt.X, lParam.pt.Y)) Then
If wParam = WM_MOUSEWHEEL Then
With oScrollableObject
Select Case GetAsyncKeyState(VBA.vbKeyControl)
Case Is = 0 'vertical scroll
If lParam.hwnd > 0 Then
.ScrollTop = Application.Max(0, .ScrollTop - SCROLL_CHANGE)
Else
.ScrollTop = Application.Min(.ScrollHeight - .InsideHeight, .ScrollTop + SCROLL_CHANGE)
End If
Case Else ' horiz scroll when the Ctl key down
If lParam.hwnd > 0 Then
.ScrollLeft = Application.Max(0, .ScrollLeft - SCROLL_CHANGE)
Else
.ScrollLeft = Application.Min(.ScrollWidth - .InsideWidth, .ScrollLeft + SCROLL_CHANGE)
End If
End Select
End With
End If
End If
MouseProc = CallNextHookEx( _
lMouseHook, nCode, wParam, ByVal lParam)
Exit Function
errH:
RemoveScrollHook
End Function
Private Function ScreenDPI(bVert As Boolean) As Long
Static lDPI(1), lDC
If lDPI(0) = 0 Then
lDC = GetDC(0)
lDPI(0) = GetDeviceCaps(lDC, LOGPIXELSX)
lDPI(1) = GetDeviceCaps(lDC, LOGPIXELSY)
lDC = ReleaseDC(0, lDC)
End If
ScreenDPI = lDPI(Abs(bVert))
End Function
Private Function PTtoPX _
(Points As Single, bVert As Boolean) As Long
PTtoPX = Points * ScreenDPI(bVert) / POINTSPERINCH
End Function
Private Function IsObjectUserForm(ByVal obj As Object) As Boolean
Dim oTemp As Object
On Error Resume Next
Set oTemp = obj.Parent
Set oTemp = Nothing
IsObjectUserForm = Err.Number = 438
On Error GoTo 0
End Function