Excel vba spinbutton textbox

Содержание

  1. VBA Excel. Элемент управления SpinButton (счетчик)
  2. Элемент управления SpinButton
  3. Свойства элемента SpinButton
  4. Пример кода VBA Excel со счетчиком
  5. Условие
  6. Решение
  7. EXCEL VIDEO TUTORIALS / EXCEL DASHBOARD REPORTS
  8. TextBox and SpinButtons UserForm Controls
  9. | BACK TO EXCEL VBA LEVEL 2 TRAINING INDEX
  10. Excel Training VBA 2 Lesson 14
  11. TextBox and SpinButtons UserForm Controls
  12. Information Helpful? Why Not Donate | Free Excel Help >> Excel Training-Video Series >> Build Trading Models In Excel | BACK TO EXCEL VBA LEVEL 2 TRAINING INDEX

VBA Excel. Элемент управления SpinButton (счетчик)

Элемент управления пользовательской формы SpinButton, применяемый в VBA Excel для создания счетчика, состоящего из двух кнопок. Свойства, пример кода.

Элемент управления SpinButton

Элемент управления SpinButton предназначен в VBA Excel для ввода пользователем числовых данных, которые ограничены минимальным и максимальным значениями. Увеличение или уменьшение числового значения счетчика при однократном нажатии кнопки происходит с указанным шагом.

Визуально, элемент управления SpinButton состоит из двух кнопок, расположенных вертикально или горизонтально в зависимости от настроек. При нажатии на верхнюю или правую кнопку элемента управления значение увеличивается, при нажатии на нижнюю или левую – уменьшается.

Обычно счетчик используется в паре с элементом управления TextBox или Label. Вспомогательный элемент необходим, чтобы отобразить значение счетчика на пользовательской форме.

Свойства элемента SpinButton

Свойство Описание
BackColor Цвет кнопок.
Delay* Время между последовательными событиями при удержании кнопки.
ControlTipText Текст всплывающей подсказки при наведении курсора на счетчик.
Enabled Возможность взаимодействия пользователя с элементом управления. True – взаимодействие включено, False – отключено (цвет стрелок становится серым).
Height Высота элемента управления.
Left Расстояние от левого края внутренней границы пользовательской формы до левого края элемента управления.
Max Максимальное значение свойства Value.
Min Минимальное значение свойства Value.
Orientation** Задает горизонтальную или вертикальную ориентацию элемента управления SpinButton.
SmallChange Шаг изменения значения свойства Value.
TabIndex Определяет позицию элемента управления в очереди на получение фокуса при табуляции, вызываемой нажатием клавиш «Tab», «Enter». Отсчет начинается с 0.
Top Расстояние от верхнего края внутренней границы пользовательской формы до верхнего края элемента управления.
Visible Видимость элемента SpinButton. True – элемент отображается на пользовательской форме, False – скрыт.
Width Ширина элемента управления.

* По умолчанию свойство Delay равно 50 миллисекундам. Это означает, что первое событие (SpinUp, SpinDown, Change) происходит через 250 миллисекунд после нажатия кнопки, а каждое последующее событие – через каждые 50 миллисекунд (и так до отпускания кнопки).

** По умолчанию включена автоматическая ориентация, которая зависит от соотношения между шириной и высотой элемента управления. Если ширина больше высоты – ориентация горизонтальная, если высота больше ширины – ориентация вертикальная.

В таблице перечислены только основные, часто используемые свойства счетчика. Все доступные свойства отображены в окне Properties элемента управления SpinButton.

Пример кода VBA Excel со счетчиком

Условие

  1. На пользовательской форме UserForm1 расположены элементы управления SpinButton1 и Label1.
  2. Необходимо задать для счетчика SpinButton1 интервал значений от 100 до 500 единиц с шагом 50 и отображением набранного значения на элементе Label1.

Решение

Первоначальные настройки при открытии пользовательской формы:

Источник

EXCEL VIDEO TUTORIALS / EXCEL DASHBOARD REPORTS

TextBox and SpinButtons UserForm Controls

| BACK TO EXCEL VBA LEVEL 2 TRAINING INDEX

Workbook Download
This is a zipped Excel Workbook to go with this lesson.

TextBox and SpinButtons

The Control Toolbox within the Visual Basic Editor by default will hold only the most commonly used controls. With just these Controls you will often find that they can be manipulated and programmed to do most if not all of what would be expected of most projects. Take for example the TextBox Control (possibly the most frequently used Control). Just because it is called a TextBox, by no means means that we are limited to only using text in this Control. While the default for this Control is to return text, it can also just as easily return numeric values.

Let’s now look at some examples of how we could use a TextBox.

Most often a TextBox Control would be used to collect typed information from a user. In previous lessons we looked at the fact that the user may mistype their information so we need to include as much validation checking as we possibly can. Obviously if the user will be typing their name there is no validation check that we can really do unless of course we have a list of all possible names that would be entered into it in which case we would end up using a ComboBox to store these names. Let’s assume for a moment that we are going to use our TextBox in this instance to collect a numeric value from the user. We could simply allow the user to type in a number and/or use the SpinButton Control to increment up to the desired number.

The SpinButton Control simply increments and decrements a number. The default Property for a SpinButton is the Value Property, while the default Event for a SpinButton is the Change Event.

Try this simple example to help better understand the SpinButton Control.

Insert a UserForm

On it place a TextBox

To the right of the Textbox place a SpinButton

Right click on the SpinButton and select Properties to display the Property Window for the SpinButton

Take a moment to look through these properties and you will notice that most of them are common to many other Controls.

Double click the SpinButton Control and within the default Change Event type TextBox1.Value=SpinButton1.Value

Now run your UserForm and user your SpinButton control to increment or decrement a number.

You will notice that by default the lowest value we can reach is 0, with the highest value being 100. If you have not guessed already, this can be easily changed in the Properties window for the SpinButton under the Max and Min Properties. So let’s go into this spot now and change this minimum and maximum to any two numbers. While you are there, also notice the Property called SmallChange. This simply tells our SpinButton what value to increment by. The default is 1, but we can change this to any value that fits within the scope of a Long, ie; -2, 147, 483, 648 to 2, 147, 483, 647. But having said this the recommended range of values ( (according to Excel’s help) is from -32,767 to 32,767. Let’s change the SmallChange Property of the SpinButton to 2. Now run your UserForm again and use the SpinButton to increment or decrement your number. This time you will be incrementing up by a step value of 2 until you reach the value set in your Max Property and down until you reach the Min Property set. This is the use of the SpinButton in possibly its simplest form. But don’t confuse this as being the same as the SpinButton being a very simple control and not having much scope of purpose. If you think about it, the whole basis of computers and Excel especially are simply built on numeric values. By this I mean that we could use the SpinButton Control to allow the user to do almost anything and you will be surprised at how many users find it more convenient to increment up/down to a number rather than type it. Not only does this help the User, but it can also aid us greatly in the fact that we can validate the TextBox storing the number to fit between a certain range and pattern without having to put in some lengthy code to validate the number chosen.

To ensure that the user cannot type into the TextBox a specific number, all we need to do is either change the Enabled Property of the TextBox to FALSE and/or the Locked Property. Once we have done this we can assume as safely as possible that the number chosen by the user using the SpinButton will meet any given criteria that we have determined.

Let us now assume we have a scenario where we have a TextBox always defaulting to today’s date and we want the user to be able to increment that date by one day up to any day one year ahead. To allow the user to simply add say 21 days to a date, is fraught with potential disasters. Let us use an example now with our TextBox to see how we can use the SpinButton to do this safely.

Double click the UserForm

Change the default Click Event to the Initialise Event

Within here place TextBox1.Value = Format(Date, «ddd d mmm yyyy»)

Above your TextBox add a Label Control and change its Caption Property to read today’s date.

Now within the SpinButton1_Change Event change our existing code to TextBox1.Value=Format(Date + SpinButton1.Value, «ddd d mmm yyyy») and below this type Label1.Caption=SpinButton1.Value & » day(s) from now»

Change the Min Property of the SpinButton to 0 and the Max Property of the SpinButton to 365

Increase the TextBox width so it will display the date in the format chosen

Run your UserForm

As soon as the UserForm shows our TextBox will display the current date including the name of the current day. Now use your SpinButton control to increment the date by 1 day at a time. You will notice that the date in the TextBox will increment by one day each time. Using this method you can ensure that the User will not type an invalid date that is not recognized by Excel or miscalculate the date from the number of days chosen. In fact, it would be impossible to do so.

One Control that Excel has which is not shown by default is the Calendar Control. This is a very handy Control to use when dates are required to be collected from the user. Not only does it make our life easier but also the user, as they can visually see a real calendar.

What I would like you to do using all available resources is create a small project that would allow a user to nominate certain dates and have them passed back to specific cells as shown in the attached Workbook. I am purposely NOT telling you how this Control works as it is very important at this level you are able to work out problems and overcome them.

Once you have had a go at this go here for some examples etc of this great Control:

Источник

Excel Training VBA 2 Lesson 14

TextBox and SpinButtons UserForm Controls

Information Helpful? Why Not Donate | Free Excel Help >> Excel Training-Video Series >> Build Trading Models In Excel
| BACK TO EXCEL VBA LEVEL 2 TRAINING INDEX

Workbook Download
This is a zipped Excel Workbook to go with this lesson.

TextBox and SpinButtons

The Control Toolbox within the Visual Basic Editor by default will hold only the most commonly used controls. With just these Controls you will often find that they can be manipulated and programmed to do most if not all of what would be expected of most projects. Take for example the TextBox Control (possibly the most frequently used Control). Just because it is called a TextBox, by no means means that we are limited to only using text in this Control. While the default for this Control is to return text, it can also just as easily return numeric values.

Let’s now look at some examples of how we could use a TextBox.

Most often a TextBox Control would be used to collect typed information from a user. In previous lessons we looked at the fact that the user may mistype their information so we need to include as much validation checking as we possibly can. Obviously if the user will be typing their name there is no validation check that we can really do unless of course we have a list of all possible names that would be entered into it in which case we would end up using a ComboBox to store these names. Let’s assume for a moment that we are going to use our TextBox in this instance to collect a numeric value from the user. We could simply allow the user to type in a number and/or use the SpinButton Control to increment up to the desired number.

The SpinButton Control simply increments and decrements a number. The default Property for a SpinButton is the Value Property, while the default Event for a SpinButton is the Change Event.

Try this simple example to help better understand the SpinButton Control.

Insert a UserForm

On it place a TextBox

To the right of the Textbox place a SpinButton

Right click on the SpinButton and select Properties to display the Property Window for the SpinButton

Take a moment to look through these properties and you will notice that most of them are common to many other Controls.

Double click the SpinButton Control and within the default Change Event type TextBox1.Value=SpinButton1.Value

Now run your UserForm and user your SpinButton control to increment or decrement a number.

You will notice that by default the lowest value we can reach is 0, with the highest value being 100. If you have not guessed already, this can be easily changed in the Properties window for the SpinButton under the Max and Min Properties. So let’s go into this spot now and change this minimum and maximum to any two numbers. While you are there, also notice the Property called SmallChange. This simply tells our SpinButton what value to increment by. The default is 1, but we can change this to any value that fits within the scope of a Long, ie; -2, 147, 483, 648 to 2, 147, 483, 647. But having said this the recommended range of values ( (according to Excel’s help) is from -32,767 to 32,767. Let’s change the SmallChange Property of the SpinButton to 2. Now run your UserForm again and use the SpinButton to increment or decrement your number. This time you will be incrementing up by a step value of 2 until you reach the value set in your Max Property and down until you reach the Min Property set. This is the use of the SpinButton in possibly its simplest form. But don’t confuse this as being the same as the SpinButton being a very simple control and not having much scope of purpose. If you think about it, the whole basis of computers and Excel especially are simply built on numeric values. By this I mean that we could use the SpinButton Control to allow the user to do almost anything and you will be surprised at how many users find it more convenient to increment up/down to a number rather than type it. Not only does this help the User, but it can also aid us greatly in the fact that we can validate the TextBox storing the number to fit between a certain range and pattern without having to put in some lengthy code to validate the number chosen.

To ensure that the user cannot type into the TextBox a specific number, all we need to do is either change the Enabled Property of the TextBox to FALSE and/or the Locked Property. Once we have done this we can assume as safely as possible that the number chosen by the user using the SpinButton will meet any given criteria that we have determined.

Let us now assume we have a scenario where we have a TextBox always defaulting to today’s date and we want the user to be able to increment that date by one day up to any day one year ahead. To allow the user to simply add say 21 days to a date, is fraught with potential disasters. Let us use an example now with our TextBox to see how we can use the SpinButton to do this safely.

Double click the UserForm

Change the default Click Event to the Initialise Event

Within here place TextBox1.Value = Format(Date, «ddd d mmm yyyy»)

Above your TextBox add a Label Control and change its Caption Property to read today’s date.

Now within the SpinButton1_Change Event change our existing code to TextBox1.Value=Format(Date + SpinButton1.Value, «ddd d mmm yyyy») and below this type Label1.Caption=SpinButton1.Value & » day(s) from now»

Change the Min Property of the SpinButton to 0 and the Max Property of the SpinButton to 365

Increase the TextBox width so it will display the date in the format chosen

Run your UserForm

As soon as the UserForm shows our TextBox will display the current date including the name of the current day. Now use your SpinButton control to increment the date by 1 day at a time. You will notice that the date in the TextBox will increment by one day each time. Using this method you can ensure that the User will not type an invalid date that is not recognized by Excel or miscalculate the date from the number of days chosen. In fact, it would be impossible to do so.

One Control that Excel has which is not shown by default is the Calendar Control. This is a very handy Control to use when dates are required to be collected from the user. Not only does it make our life easier but also the user, as they can visually see a real calendar.

What I would like you to do using all available resources is create a small project that would allow a user to nominate certain dates and have them passed back to specific cells as shown in the attached Workbook. I am purposely NOT telling you how this Control works as it is very important at this level you are able to work out problems and overcome them.

Once you have had a go at this go here for some examples etc of this great Control:

Источник

Элемент управления пользовательской формы SpinButton, применяемый в VBA Excel для создания счетчика, состоящего из двух кнопок. Свойства, пример кода.

UserForm.SpinButton – это элемент управления пользовательской формы, представляющий из себя счетчик, состоящий из двух кнопок, нажатие на которые увеличивает или уменьшает числовое значение этого элемента с указанным шагом.

Элемент управления SpinButton
Элемент управления SpinButton предназначен в VBA Excel для ввода пользователем числовых данных, которые ограничены минимальным и максимальным значениями. Увеличение или уменьшение числового значения счетчика при однократном нажатии кнопки происходит с указанным шагом.

Визуально, элемент управления SpinButton состоит из двух кнопок, расположенных вертикально или горизонтально в зависимости от настроек. При нажатии на верхнюю или правую кнопку элемента управления значение увеличивается, при нажатии на нижнюю или левую – уменьшается.

Обычно счетчик используется в паре с элементом управления TextBox или Label. Вспомогательный элемент необходим, чтобы отобразить значение счетчика на пользовательской форме.

Свойства элемента SpinButton

Свойство Описание
BackColor Цвет кнопок.
Delay* Время между последовательными событиями при удержании кнопки.
ControlTipText Текст всплывающей подсказки при наведении курсора на счетчик.
Enabled Возможность взаимодействия пользователя с элементом управления. True – взаимодействие включено, False – отключено (цвет стрелок становится серым).
Height Высота элемента управления.
Left Расстояние от левого края внутренней границы пользовательской формы до левого края элемента управления.
Max Максимальное значение свойства Value.
Min Минимальное значение свойства Value.
Orientation** Задает горизонтальную или вертикальную ориентацию элемента управления SpinButton.
SmallChange Шаг изменения значения свойства Value.
TabIndex Определяет позицию элемента управления в очереди на получение фокуса при табуляции, вызываемой нажатием клавиш «Tab», «Enter». Отсчет начинается с 0.
Top Расстояние от верхнего края внутренней границы пользовательской формы до верхнего края элемента управления.
Visible Видимость элемента SpinButton. True – элемент отображается на пользовательской форме, False – скрыт.
Width Ширина элемента управления.

* По умолчанию свойство Delay равно 50 миллисекундам. Это означает, что первое событие (SpinUp, SpinDown, Change) происходит через 250 миллисекунд после нажатия кнопки, а каждое последующее событие – через каждые 50 миллисекунд (и так до отпускания кнопки).

** По умолчанию включена автоматическая ориентация, которая зависит от соотношения между шириной и высотой элемента управления. Если ширина больше высоты – ориентация горизонтальная, если высота больше ширины – ориентация вертикальная.

В таблице перечислены только основные, часто используемые свойства счетчика. Все доступные свойства отображены в окне Properties элемента управления SpinButton.

Пример кода VBA Excel со счетчиком

Условие

  1. На пользовательской форме UserForm1 расположены элементы управления SpinButton1 и Label1.
  2. Необходимо задать для счетчика SpinButton1 интервал значений от 100 до 500 единиц с шагом 50 и отображением набранного значения на элементе Label1.

Решение

Первоначальные настройки при открытии пользовательской формы:

Private Sub UserForm_Initialize()

Me.Caption = «Пример»

  With SpinButton1

    .Min = 100

    .Max = 500

    .SmallChange = 50

  End With

Label1.Caption = «100»

End Sub

Обработка события Change объекта SpinButton1:

Private Sub SpinButton1_Change()

  Label1.Caption = SpinButton1.Value

End Sub

Обе процедуры размещаются в модуле пользовательской формы.

 

Добрый день ВСЕМ!  

  Необходимо устанавливать SpinButton значения в дробном формате в TextBox,  
при этом выбранное значение должно учитываться в формуле, формула в лист  
записывается макросом!    

  Подскажите, как сие можно осуществить и можно ли вообще?  
Подробности в примере

 

1) Me.SpinButton1.Value всегда целое от  Me.SpinButton1.Min до  Me.SpinButton1.max  
2) Раз вы хотите настроить пределы значений  в SpinButton:  MIN = 1/8 = 6/48     MAX = 2/3 =26/48    
устанавливаем в свойствах SpinButton MIN = 6     MAX = 26  
при этом шаг у нас 1/48, и числовое значение коэффициента определяется как  
Me.SpinButton1.Value / 48  
3) показать число в дробном формате  
WorksheetFunction.Text(Me.SpinButton1.Value / 48, «# ???/???») здесь оставлено три значащих цифры про запас, при шаге 1/48 достаточно двух  
4) вобще говоря значение SpinButton1.Value сохраняется, но если нужно начинать с 1/8 то  
Private Sub UserForm_Initialize()  
Me.SpinButton1.Value = Me.SpinButton1.Min  
Me.TextBox1 = WorksheetFunction.Text(Me.SpinButton1.Value / 48, «# ???/???»)  
End Sub  
5) запись числа в textbox в дробном формате и добавление в формулу  
Private Sub SpinButton1_Change()  
Me.TextBox1 = WorksheetFunction.Text(Me.SpinButton1.Value / 48, «# ???/???»)  
Range(«J2»).Formula = «=ROUND(ROUND(($E2*$G2*» & Me.TextBox1.Value & «),0)-H2,0)»  
End Sub  

  ну вот и все пироги….

 

26/48 = 13/24 = 2/3-1/8 это диапазон изменения, чтоб определить допустимый шаг.  

  вместо  
устанавливаем в свойствах SpinButton MIN = 6 MAX = 26  
надо  
устанавливаем в свойствах SpinButton MIN = 6 MAX = 32 (тогда от 1/8 до 2/3)

 

Большое спасибо dl за содействие!  

  Проверил, все хорошо, респект!  

  Sofi

 

Уважаемый dl и остальные форумчане!  

  Поковырялся с Вашим вариантом решения моей проблемы и  
возник вопрос по предложенному Вами форматированию, только  
применительно к ComboBox!  

  Подробности в примере!

 

GIG_ant

Пользователь

Сообщений: 3102
Регистрация: 24.12.2012

А чем вам не подходит:  
Me.ComboBox1.List = Array(«1 / 2», «1 / 3», «1 / 4», «1 / 5», «1 / 6», «1 / 7», «1 / 8») ??  

  Все отображается так как надо.

 

GIG_ant

Пользователь

Сообщений: 3102
Регистрация: 24.12.2012

что бы получить численное значение дроби используйте функцию: Evaluate(), см. файл.

 

Sofi

Гость

#8

19.04.2011 10:23:57

Действительно, все как надо!  

  У меня почему-то в Combo.List были дроби 1/2 и т.д.  
а в окне Combo  «40548» т.е. ДАТА!  

  Странно,    
спасибо за участие!

A SpinButton has a Value property, but this control doesn’t have a caption in which to display its value. In many cases, however, you will want the user to see the SpinButton value. And sometimes you’ll want the user to be able to change the SpinButton value directly instead of clicking the SpinButton repeatedly.

The solution is to pair a SpinButton with a TextBox, which enables the user to specify a value either by typing it into the TextBox directly or by clicking the SpinButton to increment or decrement the value in the TextBox.

Figure 13-13 shows a simple example. The SpinButton’s Min property is 1, and its Max property is 100. Therefore, clicking the SpinButton’s arrows will change its value to an integer between 1 and 100.

SpinButton / TextBox Demo

Specify 5 value befr een 1 and 100:

| 3: jj

! OK

Figure 13-13: This SpinButton is paired with a TextBox.

Figure 13-13: This SpinButton is paired with a TextBox.

CD- This workbook is available on the companion CD-ROM. The file is named spinbutton ROM and textbox. xlsm.

The code required to link a SpinButton with a TextBox is relatively simple. It’s basically a matter of writing event handler procedures to ensure that the SpinButton’s Value property is always in sync with the TextBox’s Text property.

The following procedure is executed whenever the SpinButton’s Change event is triggered. That is, the procedure is executed when the user clicks the SpinButton or changes its value by pressing the up arrow or down arrow.

Private Sub SpinButton1_Change()

TextBoxl.Text = SpinButtonl.Value End Sub

The procedure simply assigns the SpinButton’s Value to the Text property of the TextBox control. Here, the controls have their default names (SpinButtonl and TextBoxl). If the user enters a value directly into the TextBox, its Change event is triggered, and the following procedure is executed:

Private Sub TextBoxl_Change()

NewVal = Val(TextBoxl.Text) If NewVal >= SpinButtonl.Min And _

NewVal <= SpinButtonl.Max Then _ SpinButtonl.Value = NewVal

End Sub

This procedure starts by using VBA’s Val function to convert the text in the TextBox to a value. (If the TextBox contains non-numeric text, the Val function returns 0.) The next statement determines whether the value is within the proper range for the SpinButton. If so, the SpinButton’s Value property is set to the value entered in the TextBox.

The example is set up so that clicking the OK button (which is named OKButton) transfers the SpinButton’s value to the active cell. The event handler for this CommandButton’s Click event is as follows:

Private Sub OKButton_Click() ‘ Enter the value into the active cell

If CStr(SpinButton1.Value) = TextBox1.Text Then ActiveCell = SpinButton1.Value Unload Me

Else

MsgBox «Invalid entry.», vbCritical TextBox1.SetFocus TextBox1.SelStart = 0

TextBox1.SelLength = Len(TextBox1.Text) End If End Sub

About the Tag Property

Every UserForm and control has a Tag property. This property doesn’t represent anything specific, and, by default, is empty. You can use the Tag property to store information for your own use.

For example, you might have a series of TextBox controls in a UserForm. The user may be required to enter text into some but not all of them. You can use the Tag property to identify (for your own use) which fields are required. In this case, you can set the Tag property to a string such as Required. Then when you write code to validate the user’s entries, you can refer to the Tag property.

The following example is a function that examines all TextBox controls on UserForm1 and returns the number of required TextBox controls that are empty:

Function EmptyCount() Dim ctl As Control EmptyCount= 0

For Each ctl In UserForm1.Controls If TypeName(ctl) = «TextBox» Then If ctl.Tag = «Required» Then If ctl.Text = «» Then

EmptyCount = EmptyCount + 1 End If End If End If Next ctl End Function

As you work with UserForms, you will probably think of other uses for the Tag property._

This procedure does one final check: It makes sure that the text entered in the TextBox matches the SpinButton’s value. This is necessary in the case of an invalid entry. For example, if the user enters 3r into the TextBox, the SpinButton’s value would not be changed, and the result placed in the active cell would not be what the user intended. Notice that the SpinButton’s Value property is converted to a string by using the CStr function. This ensures that the comparison will not generate an error if a value is compared with text. If the SpinButton’s value does not match the TextBox’s contents, a message box is displayed. Notice that the focus is set to the TextBox object, and the contents are selected (by using the SelStart and SelLength properties). This makes it very easy for the user to correct the entry.

4 PREV

NEXT

Continue reading here: Adding new ActiveX controls

Was this article helpful?

SpinButtons at first glance look clunky and unnecessary:

A spinner control

The
SpinButton allows the user to change the number of sugars ordered.

However, the reason that they are so useful is that they allow you to prevent
users typing in numbers directly:

Enabled property of textbox

The textbox for the number of sugars has the
Enabled property set to False — this means that a user can’t change the value directly.

If a user can’t type in a number directly, you don’t have to validate its
data type or values.  This is a big advantage!

Creating a SpinButton

To create a SpinButton, just click on the tool and then click where you want
it to go:

The SpinButton tool

Don’t confuse the
SpinButton tool with the scroll bar tool …

A SpinButton usually sits next to the textbox whose value it will affect:

A SpinButton next to a textbox

Here the SpinButton will control the value in the
txtSugar textbox.

That’s the easy part.  When you double-click on the SpinButton to write
code, you get an odd default event:

Private Sub spnSugar_Change()

End Sub

It’s more likely that you would attach code to the SpinDown
and SpinUp events.

Writing a Generic Procedure to Handle Spinning Up and Down

It’s good programming practice to write a single procedure to handle both
possible spin directions.  For our example, this could be:

Sub AddSugar(NumberAdd As Integer)

Dim CurrentSugars As Integer

CurrentSugars = CInt(Me.txtSugar.Text)

CurrentSugars = CurrentSugars + NumberAdd

txtSugar.Text = IIf(CurrentSugars > 0, CurrentSugars, 0)

End Sub

Here we’ll pass in the number of sugars to add (this can be negative). 
The routine makes sure that you don’t set the number of sugars to be less than
0.

Attaching Code to the SpinButton Events

If you’ve written a generic procedure as above, you just need to call it
twice — once when you spin up, and once when you spin down:

Private Sub spnSugar_SpinDown()

AddSugar -1

End Sub

Private Sub spnSugar_SpinUp()

AddSugar 1

End Sub

When you click on the down arrow of the SpinButton, for example, it will call
the AddSugar routine to add -1 sugars.

Понравилась статья? Поделить с друзьями:
  • Excel vba source control
  • Excel vba sorting function
  • Excel vba sort function
  • Excel vba solver макрос описание параметров
  • Excel vba sheets или worksheets