Vba excel checkbox click

Элемент управления пользовательской формы CheckBox для выбора или невыбора его пользователем и передачи результата в VBA Excel. Свойства «Флажка», примеры кода.

UserForm.CheckBox – это элемент управления пользовательской формы, предназначенный для передачи в код VBA информации о выборе или невыборе его пользователем и возвращающий одно из двух значений: False (галочки нет) или True (галочка установлена).

Элемент управления CheckBox на пользовательской форме

Элемент управления CheckBox состоит из флажка и надписи. В VBA Excel флажок имеет квадратную форму, надпись расположена справа от него. Надпись реагирует на нажатие мышью так же, как и флажок.

По тексту статьи значение слова «Флажок» в кавычках равно значению слова CheckBox, флажок без кавычек обозначает квадрат с галочкой или без нее.

Кроме состояний «выбран» или «не выбран», существует и третье состояние флажка: серая галочка на сером фоне. Получить такое состояние на пользовательской форме можно путем присвоения свойству CheckBox.Value значения Null.

Три состояния элемента управления CheckBox

Надписи флажков выведены с помощью следующего кода VBA Excel:

Private Sub UserForm_Initialize()

CheckBox1.Value = False

CheckBox1.Caption = «CheckBox1.Value = « _

& CheckBox1.Value

CheckBox2.Value = Null

CheckBox2.Caption = «CheckBox2.Value = « _

& CheckBox2.Value

CheckBox3.Value = True

CheckBox3.Caption = «CheckBox3.Value = « _

& CheckBox3.Value

End Sub

Интересно было посмотреть, какое значение отобразится в надписи элемента управления CheckBox2. Обратите внимание на то, что если строку CheckBox2.Caption = "CheckBox2.Value = " & CheckBox2.Value заменить на CheckBox2.Caption = CheckBox2.Value, будет сгенерирована ошибка, так как в VBA не существует текстового отображения значения Null.

Эксперименты показали, что отобразить «Флажок» в третьем состоянии можно также с помощью присвоения свойству CheckBox.Value значения «пустая строка».

Элемент управления CheckBox может использоваться на пользовательской форме для

  • выбора или отмены каких-либо параметров и условий,
  • отображения или скрытия других элементов управления,
  • изменение доступности других элементов управления для взаимодействия с пользователем.

Если требуется выбор только одной опции из группы предложенных, для этой цели в VBA Excel используется набор элементов управления OptionButton.

Свойства элемента «Флажок»

Свойство Описание
AutoSize Автоподбор размера «Флажка». True – размер автоматически подстраивается под длину набираемой строки. False – размер элемента управления определяется свойствами Width и Height.
ControlSource Ссылка на источник данных для свойства Value.
ControlTipText Текст всплывающей подсказки при наведении курсора на CheckBox.
Enabled Возможность взаимодействия пользователя с элементом управления. True – взаимодействие включено, False – отключено (цвет флажка и надписи становится серым).
Font Шрифт, начертание и размер текста надписи.
Height Высота элемента управления.
Left Расстояние от левого края внутренней границы пользовательской формы до левого края элемента управления.
Picture Добавление изображения вместо текста надписи или дополнительно к нему.
PicturePosition Выравнивание изображения и текста в поле надписи.
TabIndex Определяет позицию элемента управления в очереди на получение фокуса при табуляции, вызываемой нажатием клавиш «Tab», «Enter». Отсчет начинается с 0.
TextAlign* Выравнивание текста надписи: 1 (fmTextAlignLeft) – по левому краю, 2 (fmTextAlignCenter) – по центру, 3 (fmTextAlignRight) – по правому краю.
Top Расстояние от верхнего края внутренней границы пользовательской формы до верхнего края элемента управления.
TripleState Определяет, может ли пользователь делать выбор между двумя состояниями «Флажка» или между тремя, включая серую галочку на сером квадрате. True – доступны три состояния, False – доступны два состояния.
Value Значение «Флажка»: True – галочка установлена, False – галочка не установлена, Null – серая галочка на сером квадрате.
Visible Видимость элемента CheckBox. True – элемент отображается на пользовательской форме, False – скрыт.
Width Ширина элемента управления.
WordWrap Перенос текста надписи на новую строку при достижении границы ее поля. True – перенос включен, False – перенос выключен.

* При загруженной в поле надписи картинке свойство TextAlign не работает, следует использовать свойство PicturePosition.

Свойство по умолчанию для элемента CheckBox – Value, основное событие – Click.

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

Примеры использования CheckBox

Пример 1
Отображение элемента управления CheckBox на пользовательской форме с параметрами, заданными в коде VBA Excel:

Private Sub UserForm_Initialize()

  With CheckBox1

    .Caption = «Нажмите на меня»

    .ControlSource = «A1»

    .Value = False

    .Left = 12

    .Top = 12

  End With

End Sub

Элемент управления CheckBox, привязанный к ячейке

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

Если несколько элементов управления CheckBox привязать к одной ячейке, то при клике на одном из них, менять свое состояние будут и все остальные.

Пример 2
Смена надписи «Флажка» в зависимости от его состояния:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

‘Устанавливаем первоначальные

‘значения свойств «Флажка»

Private Sub UserForm_Initialize()

  With CheckBox1

    .Caption = «Поставьте галочку»

    .Value = False

    .TripleState = False

  End With

End Sub

‘Меняем надпись «Флажка» при

‘смене параметра CheckBox1.Value

Private Sub CheckBox1_Change()

  If CheckBox1.Value Then

    CheckBox1.Caption = «Снимите галочку»

  Else

    CheckBox1.Caption = «Поставьте галочку»

  End If

End Sub

Пример 3
Скрытие и отображение, изменение доступности других элементов управления с помощью «Флажка».

Для реализации этого примера необходимо создать пользовательскую форму с четырьмя элементами управления: CheckBox1, TextBox1, TextBox2 и CommandButton1. А в модуле формы разместить следующий код:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

‘Устанавливаем первоначальные

‘значения свойств элементов управления

Private Sub UserForm_Initialize()

  With CheckBox1

    .Caption = «Хочу сложить два числа»

    .Value = False

    .TripleState = False

  End With

  With TextBox1

    .Enabled = False

    .Text = «Слагаемое 1»

  End With

  With TextBox2

    .Enabled = False

    .Text = «Слагаемое 2»

  End With

  With CommandButton1

    .Caption = «Сложить»

    .Visible = False

  End With

End Sub

‘Меняем свойства других элементов

‘управления при смене состояния «Флажка»

Private Sub CheckBox1_Change()

  If CheckBox1.Value Then

    TextBox1.Enabled = True

    TextBox2.Enabled = True

    CommandButton1.Visible = True

  Else

    TextBox1.Enabled = False

    TextBox2.Enabled = False

    CommandButton1.Visible = False

  End If

End Sub

‘Складываем два числа

Private Sub CommandButton1_Click()

  If IsNumeric(TextBox1) And IsNumeric(TextBox2) Then

    MsgBox TextBox1 & » + « & TextBox2 & » = « _

    & CDbl(TextBox1) + CDbl(TextBox2)

  End If

End Sub

Форма открывается с недоступными для пользователя текстовыми полями и скрытой кнопкой «Сложить»:

После установки галочки на флажке текстовые поля становятся доступными для редактирования, и отображается кнопка «Сложить»:


I have 5 checkboxes to set some options for a macro, one of them is a Select/Unselect All checkbox. I want to create something similar to what you have on web-based mailboxes when you select mails to delete or mark as read, etc.
When I check the Select/Unselect All checkbox, I turn the rest of the checkboxes’s values to true and viceversa when I uncheck it. That’s ok.

The problem comes when I also want to validate that if everything is unchecked and one by one I check the other checkboxes, if in the end I check all, then the Select/Unselect All checkbox turns to checked. And viceversa, meaning that if eveything is checked and then I uncheck one of the four others, then I turn the «All» checkbox to false (unchecked).

But it seems that even when I just set the value, for example Option1Checkbox.value = True, in the SelectAllCheckbox_Click event, it triggers both the Option1Checkbox_Click and Option1Checkbox_Change events.

Shouldn’t it just trigger the Change event since I’m not actually clicking that checkbox?

What happens is that I check the SelectAll, so it turns Option1 to checked, but by doing this, Option1 triggers also the click event so it unchecks it which triggers the click event again and then unchecks again the All checkbox which in the end leaves everything unchecked, like at the beginning. Hope this part is clear enough.

How can I avoid this behavior? How can I make sure only the Change event is triggered and not the Click event?

Has anyone ever had such an arrangement of checkboxes and had a similar problem? Or how did you manage to do this without the behavior I’m getting?

The checkboxes are not on a form but simply on a worksheet. They are ActiveX controls. And what I have is nothing complicated:

Private Sub SelectAll_Click()
    Option1Checkbox.Value = SelectAll.Value
    Option2Checkbox.Value = SelectAll.Value
    Option3Checkbox.Value = SelectAll.Value
    Option4Checkbox.Value = SelectAll.Value
End Sub

Then the options checkboxes click events look like this:

Private Sub Option1Checkbox_Click()
    If Option1Checkbox.Value = True And Option2Checkbox.Value = True And Option3Checkbox.Value = True And Option4Checkbox.Value = True Then
        SelectAll.Value = True
    Else
        SelectAll.Value = False
    End If
End Sub

It’s quite simple, the biggest problem I see is the calls to the click events when the checkbox is not actually click.

Thanks for your help.

200?’200px’:»+(this.scrollHeight+5)+’px’);»> Private Sub CheckBox1_Click()
If True Then
MsgBox «Вы добаляете торцевое отверстие»
Cells(1, 1).FormulaR1C1 = _
«=RC[1]&RC[2]&RC[3]&RC[4]&RC[5]»
Else
MsgBox «Вы убрали торцевое отверстие»
Cells(1, 1).FormulaR1C1 = _
«=»»»»»»»
End If

Я пологал что должна быть лагическая форма если, но ошибся

Ну и конечно хотелось бы «заморозить» TextBoX», напротив галочики при условии если она снята.

200?’200px’:»+(this.scrollHeight+5)+’px’);»> Private Sub CheckBox1_Click()
If True Then
MsgBox «Вы добаляете торцевое отверстие»
Cells(1, 1).FormulaR1C1 = _
«=RC[1]&RC[2]&RC[3]&RC[4]&RC[5]»
Else
MsgBox «Вы убрали торцевое отверстие»
Cells(1, 1).FormulaR1C1 = _
«=»»»»»»»
End If

Я пологал что должна быть лагическая форма если, но ошибся

Ну и конечно хотелось бы «заморозить» TextBoX», напротив галочики при условии если она снята. televnoy

200?’200px’:»+(this.scrollHeight+5)+’px’);»> Private Sub CheckBox1_Click()
If True Then
MsgBox «Вы добаляете торцевое отверстие»
Cells(1, 1).FormulaR1C1 = _
«=RC[1]&RC[2]&RC[3]&RC[4]&RC[5]»
Else
MsgBox «Вы убрали торцевое отверстие»
Cells(1, 1).FormulaR1C1 = _
«=»»»»»»»
End If

Я пологал что должна быть лагическая форма если, но ошибся

Ну и конечно хотелось бы «заморозить» TextBoX», напротив галочики при условии если она снята. Автор — televnoy
Дата добавления — 19.09.2014 в 07:12

Источник

Excel VBA checkbox click and change events the same?

I have 5 checkboxes to set some options for a macro, one of them is a Select/Unselect All checkbox. I want to create something similar to what you have on web-based mailboxes when you select mails to delete or mark as read, etc. When I check the Select/Unselect All checkbox, I turn the rest of the checkboxes’s values to true and viceversa when I uncheck it. That’s ok.

The problem comes when I also want to validate that if everything is unchecked and one by one I check the other checkboxes, if in the end I check all, then the Select/Unselect All checkbox turns to checked. And viceversa, meaning that if eveything is checked and then I uncheck one of the four others, then I turn the «All» checkbox to false (unchecked).

But it seems that even when I just set the value, for example Option1Checkbox.value = True, in the SelectAllCheckbox_Click event, it triggers both the Option1Checkbox_Click and Option1Checkbox_Change events.

Shouldn’t it just trigger the Change event since I’m not actually clicking that checkbox?

What happens is that I check the SelectAll, so it turns Option1 to checked, but by doing this, Option1 triggers also the click event so it unchecks it which triggers the click event again and then unchecks again the All checkbox which in the end leaves everything unchecked, like at the beginning. Hope this part is clear enough.

How can I avoid this behavior? How can I make sure only the Change event is triggered and not the Click event?

Has anyone ever had such an arrangement of checkboxes and had a similar problem? Or how did you manage to do this without the behavior I’m getting?

The checkboxes are not on a form but simply on a worksheet. They are ActiveX controls. And what I have is nothing complicated:

Then the options checkboxes click events look like this:

It’s quite simple, the biggest problem I see is the calls to the click events when the checkbox is not actually click.

Источник

The Complete Guide to Excel VBA Form Control Checkboxes

The VBA Tutorials Blog

Table of Contents

Introduction

This VBA Guide will teach you everything you ever wanted to know about handling Excel Form Control Checkboxes using VBA. By “Form Control” checkboxes, I mean this little guy located under “Form Controls” on the Developer Tab > Insert menu:


Form Control Checkboxes

I’ve created a simple pizza order form using Excel Form Control Checkboxes. I’ll reference this order form throughout the guide as we learn how to manipulate our checkboxes with VBA macros.


Excel Pizza Order Form

Keep reading to learn how to check, uncheck, assign a macro to and loop through all form control checkboxes!

Note: If you want to learn how to control ActiveX Checkboxes, instead, head over to my Excel VBA ActiveX Checkboxes Guide.

Return the Value of your Checkbox

There’s more than one way to check the value of a form control checkbox. I’ll present three ways. The following macros return the value of a checkbox named “ Check Box 1 ” and store the value in the variable cbValue . Remember, the checkbox name can be found in the upper left of Excel when you have your checkbox selected:


Check Box 1

Method 1

Method 2

Method 3

Make powerful macros with our free VBA Developer Kit

Tutorials like this can be complicated. That’s why we created our free VBA Developer Kit and our Big Book of Excel VBA Macros to supplement this tutorial. Grab them below and you’ll be writing powerful macros in no time.

All three methods do the same thing, so you can just pick one and go with it. There are three possible values of a checkbox. Yes, three!

Value Example Description
1 Checked (xlOn)
-4146 Unchecked (xlOff)
2 Mixed (xlMixed)

Checking/Unchecking your Checkbox

Checking and unchecking your checkbox is almost identical to returning the value of your checkbox. Again, at least three methods can be used. The following macros first check the box, then uncheck the box and, finally, mix the checkbox:

Источник

Макрос активации кнопки при помощи галочки(флажка) в чекбоксе(CheckBox).

Макрос включения и отключения кнопки при помощи галочки (флажка) в CheckBox.

Иногда возникают ситуации, когда нужно включать или отключать активную кнопку при помощи галочки в поле чек бокса.

Выглядит это примерно, как отметка о согласии с лицензионным соглашением при установке программ — если стоит галочка возле надписи «Согласен» , кнопка «Далее>>» активна, в противном случае кнопка не активна.

Кнопки активации

Рассмотрим, как создать макрос, который будет активировать или деактивировать кнопку.

Для начала следует создать кнопку «CommandButton1» и чек-бокс активации «CheckBox1» на поле «UserFom1».

UserForm1

Кнопку назовем «Далее>>», а чек бокс подпишем, как «Активация кнопки».

Запись макроса на чек-бокс

В свойствах кнопки выставляем: Enabled — False

Enabled False

Как записать макрос на действия с Чек-боксом (CheckBox1) .

Шаг 1. Кликаем по CheckBox1 правой кнопкой мыши.

Шаг 2. Выбираем из выпадающего меню пункт «View Code» (показать код).

Шаг 3. В появившемся поле записываем код.

Код активации кнопки:

Private Sub CheckBox1_Click() ‘ клик по кнопке

If UserForm1.CheckBox1.Value = True Then UserForm1.CommandButton1.Enabled = True Else UserForm1.CommandButton1.Enabled = False ‘проверяет значение Чек-бокса и включает кнопку

End Sub

Макрос готов — кнопка активируется по флажку в чекбоксе.

Добавить комментарий Отменить ответ

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Источник

Adblock
detector

macsssimka

0 / 0 / 0

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

Сообщений: 9

1

Excel

12.11.2020, 19:12. Показов 4352. Ответов 9

Метки checkbox, vba excel (Все метки)


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

Добрый вечер. На листе excel создана табличка, которая заполняется при помощи формы. Данные, введённые пользователем, из формы попадают в ячейки. В ячейку последнего столбца при определенном условии заносится checkbox. Это делается в коде формы при помощи данного выражения.
ActiveSheet.CheckBoxes.add(Cells(lRow, 7).Left, Cells(lRow, 7).Top, Cells(lRow, 7).Height, Cells(lRow, 7).Height).Select
Форма закрывается. В дальнейшем при переводе checkbox в состояние checked должны быть произведены некоторые манипуляции со строкой в которой он находится. Подскажите пожалуйста как отловить данное событие?

И еще один вопросик. Для эксперимента пробовал назначит макрос руками уже существующему на листе chkbox20 и получить его значение, однако тут опять засада, почему то постоянно возвращается значение True.

Visual Basic
1
2
3
4
5
6
7
8
9
Sub chkbox20_Щелчок()
   Dim v As Boolean
   v = ActiveSheet.Shapes("chkbox20").OLEFormat.Object.Value
   MsgBox (v)
End Sub
Однако когда я записываю данное выражение в другом формате возвращается все верно 1 и -4146
Sub chkbox20_Щелчок()
   MsgBox (ActiveSheet.Shapes("chkbox20").OLEFormat.Object.Value)
End Sub



0



Rosgard

50 / 24 / 8

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

Сообщений: 98

12.11.2020, 19:27

2

Двойным кликом по checkbox и:

Visual Basic
1
2
3
4
5
Private Sub CheckBox1_Click()
If CheckBox1.Value = True Then
    'тут ставьте обработку условия
End If
End Sub



0



0 / 0 / 0

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

Сообщений: 9

12.11.2020, 19:48

 [ТС]

3

Проблема в том, что checkbox создается динамически при помощи формы по мере заполнения строк таблицы и на листе их может быть огромное количество, соответственно создавать обработчик событий для каждого checkbox руками не вариант. Поэтому я хочу написать универсальную функцию для обработки данного события, чтобы например по имени измененного пользователем состояния checkbox в i-й строке, скрипт смог обратиться к i-й строке и отформатировать ее. А вот как поймать это событие я не могу понять.



0



89 / 49 / 18

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

Сообщений: 187

12.11.2020, 20:14

4

Если будет много строк или чекбоксов Excel может тупо зависнуть. Может покажете примерный файл и опишете то, что Вы хотите получить (без чекбоксов? Не думали о том, что форматирование можно делать и без чекбоксов?



0



50 / 24 / 8

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

Сообщений: 98

12.11.2020, 20:25

5

Тогда массив контролов. Индекс массива будет соответствовать номеру строки.



0



0 / 0 / 0

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

Сообщений: 9

12.11.2020, 21:16

 [ТС]

6

Цитата
Сообщение от Igor_61
Посмотреть сообщение

Если будет много строк или чекбоксов Excel может тупо зависнуть. Может покажете примерный файл и опишете то, что Вы хотите получить (без чекбоксов? Не думали о том, что форматирование можно делать и без чекбоксов?

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

Нужно отловить изменение состояния чекбокса на листе, после чего, отредактировать строку в которой он находится.

Миниатюры

CheckBox, как отловить событие
 



0



0 / 0 / 0

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

Сообщений: 9

12.11.2020, 21:19

 [ТС]

7

Цитата
Сообщение от Rosgard
Посмотреть сообщение

Тогда массив контролов. Индекс массива будет соответствовать номеру строки.

Это все понятно, вопрос в том как само событие клика по чекбоксу отловить отловить? Дальнейшая обработка события трудностей не вызывает



0



Часто онлайн

790 / 529 / 237

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

Сообщений: 1,820

13.11.2020, 00:00

8

macsssimka, есть такой вариант, если подойдет, расскажу как ловить событие



1



TinGol

42 / 30 / 13

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

Сообщений: 141

13.11.2020, 10:04

9

Лучший ответ Сообщение было отмечено macsssimka как решение

Решение

macsssimka, что бы отловить событие, динамически созданного ActiveX объекта, можно использовать такое решение:

Создаем модуль класса с именем, к примеру «myControl»
код класа:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
' WithEvents  - позволит использовать событие в нашем классе
Private WithEvents chBox As MSForms.CheckBox
Private id_control As Long
 
' Событие
Private Sub chBox_Click()
    MsgBox "ЧекБокс [" & id_control & "] значение: " & chBox.Value
End Sub
' Сохраняем в переменную объект чекбокса
Public Property Set ItemControl(NewCtrl As MSForms.CheckBox)
    Set chBox = NewCtrl
End Property
' Получаем объект чекбокса
Public Property Get ItemControl() As MSForms.CheckBox
    Set ItemControl = chBox
End Property
'Получаем Id чекбокса
Public Property Get id() As Long
    id = id_control
End Property
' Задаем Id чекбокса
Public Property Let id(newId As Long)
    id_control = newId
End Property

Теперь можно использовать этот класс в своем модуле или модуле листа:

Visual Basic
1
2
3
4
Dim myCnt As myControl
Set myCnt = New myControl
myCnt.ItemControl = ActiveSheet.Shapes("chkbox20").OLEFormat.Object
myCnt.id = 1

все. при нажатии на чекбокс сработает событие в классе.
Если надо много чекбоксов, создавай коллекцию или массив:

Visual Basic
1
2
3
4
5
6
' массив
Public ЧекБоксы(10) As New myControl
ЧекБоксы(0).ItemControl = ActiveSheet.Shapes("chkbox20").OLEFormat.Object
ЧекБоксы(1).ItemControl = ActiveSheet.Shapes("chkbox20").OLEFormat.Object
ЧекБоксы(2).ItemControl = ActiveSheet.Shapes("chkbox20").OLEFormat.Object
...
Visual Basic
1
2
3
4
5
'Коллекция
Dim coll as new Collection 
Set myCnt.ItemControl = ActiveSheet.Shapes("chkbox20").OLEFormat.Object
myCnt.id = 1
coll.add myCnt

Добавлено через 2 минуты
Однако, как было сказано, из — за большого количества чекбоксов на листе, может все заглючить.

Добавлено через 3 минуты
Так, извиняюсь.. Это не ActiveX объект, не заметил ActiveSheet.Shapes Код работать не будет.



1



macsssimka

0 / 0 / 0

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

Сообщений: 9

13.11.2020, 15:22

 [ТС]

10

Цитата
Сообщение от TinGol
Посмотреть сообщение

macsssimka, что бы отловить событие, динамически созданного ActiveX объекта, можно использовать такое решение:

Создаем модуль класса с именем, к примеру «myControl»
код класа:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
' WithEvents  - позволит использовать событие в нашем классе
Private WithEvents chBox As MSForms.CheckBox
Private id_control As Long
 
' Событие
Private Sub chBox_Click()
    MsgBox "ЧекБокс [" & id_control & "] значение: " & chBox.Value
End Sub
' Сохраняем в переменную объект чекбокса
Public Property Set ItemControl(NewCtrl As MSForms.CheckBox)
    Set chBox = NewCtrl
End Property
' Получаем объект чекбокса
Public Property Get ItemControl() As MSForms.CheckBox
    Set ItemControl = chBox
End Property
'Получаем Id чекбокса
Public Property Get id() As Long
    id = id_control
End Property
' Задаем Id чекбокса
Public Property Let id(newId As Long)
    id_control = newId
End Property

Теперь можно использовать этот класс в своем модуле или модуле листа:

Visual Basic
1
2
3
4
Dim myCnt As myControl
Set myCnt = New myControl
myCnt.ItemControl = ActiveSheet.Shapes("chkbox20").OLEFormat.Object
myCnt.id = 1

все. при нажатии на чекбокс сработает событие в классе.
Если надо много чекбоксов, создавай коллекцию или массив:

Visual Basic
1
2
3
4
5
6
' массив
Public ЧекБоксы(10) As New myControl
ЧекБоксы(0).ItemControl = ActiveSheet.Shapes("chkbox20").OLEFormat.Object
ЧекБоксы(1).ItemControl = ActiveSheet.Shapes("chkbox20").OLEFormat.Object
ЧекБоксы(2).ItemControl = ActiveSheet.Shapes("chkbox20").OLEFormat.Object
...
Visual Basic
1
2
3
4
5
'Коллекция
Dim coll as new Collection 
Set myCnt.ItemControl = ActiveSheet.Shapes("chkbox20").OLEFormat.Object
myCnt.id = 1
coll.add myCnt

Добавлено через 2 минуты
Однако, как было сказано, из — за большого количества чекбоксов на листе, может все заглючить.

Добавлено через 3 минуты
Так, извиняюсь.. Это не ActiveX объект, не заметил ActiveSheet.Shapes Код работать не будет.

Отлично, спасибо за решение, буду просто создавать activex checkbox

Добавлено через 3 минуты

Цитата
Сообщение от КостяФедореев
Посмотреть сообщение

macsssimka, есть такой вариант, если подойдет, расскажу как ловить событие

Кстати очень даже оригинально, об этом я не подумал, тоже достаточно интересное решение, спасибо большое



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

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

13.11.2020, 15:22

10

“I want to think that there is someone with sound judgement at the controls” – Martin Feldstein

The Webinar

If you are a member of the website, click on the image below to view the webinar for this post.

(Note: Website members have access to the full webinar archive.)

vba userform2 video

Introduction

In the first post on UserForms we looked at the general use of the UserForm.

In this post we are going to look at the individual VBA controls and how to use them. We will cover the most commonly used VBA controls. These are the Checkbox, ComboBox, CommandButton, Label, ListBox and TextBox. For each control, I will cover their most common uses and provide plenty of code examples you can use in your own projects.

The UserForm Controls

We add controls to the UserForms to allow the user to make selections, enter text or click a button. To add a control to a UserForm we do the following

  1. Go to the Toolbox dialog – if not visible select View->Toolbox.
  2. Click on the control icon you want to add – the icon will appear selected(pressed in) until you click another one.
  3. Put the cursor over the UserForm.
  4. Hold down the left mouse button and drag until the control is the size you want.
  5. To select or move a control click on the Select Objects icon(very left one) on the toolbox and this will put you in select mode.

 
The following table shows a list of the common controls

Control Description
CheckBox Turn item on/off
ComboBox Allows selection from a list of items
CommandButton Click to perform action
Label Displays text
ListBox Allows selection from a list of items
Textbox Allows text entry

Properties of the Controls

The screenshot below shows the three important Windows when adding controls to a UserForm. These are

  1. The Properties Window.
  2. The Toolbox Dialog.
  3. The UserForm design Window.

VBA UserForm

UserForm Windows

 
If you click on any control or the UserForm itself you will see the properties of the selected item displayed in the Properties window. You can change the name, caption etc. in this Window.

To change the name of the UserForm do the following

  1. Click on the UserForm in the Project window or click on the UserForm itself.
  2. Click in the (Name) field of the Properties window.
  3. Enter the new name in this field.

Adding the Code

You can view the code of the UserForm in the following ways
 

  1. Double click on the UserForm.
  2. Right click on the UserForm itself and select View Code.
  3. Right click on the UserForm in the Project windows and select View Code.

Common control functions

The following table shows the most commonly used functions that are available to all controls.

Function Operation Example
Enabled Enable/Disable control combobox.Enabled = True
textbox.Enabled = False
SetFocus Sets the focus to the control
(cannot use with the Label)
combobox.SetFocus
Visible Show/Hide control combobox.Visible = True
textbox.Visible = False
' https://excelmacromastery.com/
Private Sub checkboxAddNotes_Click()

    ' Enable texbox when checkbox set to true
    If checkboxAddNotes.Value = True Then
        textboxNotes.Enabled = True
        textboxNotes.SetFocus
    Else
        textboxNotes.Enabled = False
    End If
         
End Sub	 

The CheckBox

The CheckBox Cheat Sheet

Function Operation Example
Caption Get/Set the text checkbox.Caption = «Apple»
Value Get the checked state If checkbox.Value = True Then
Value Set the checked state checkbox.Value = False

 
The CheckBox is a simple control that allows the user set something to on or off. You will often see them used on web pages where you are asked to accept terms and conditions.

 
VBA Checkbox

Turning the CheckBox on or off

We can turn the CheckBox on or off by setting it to true or false

' Set the check on
CheckBoxTerms.Value = True

' Set the check off
CheckBoxTerms.Value = False

Checkbox Event with example

If we want to create an action when the user clicks on the checkbox then we create a checkbox event. This is simply a sub that runs when the checkbox is clicked.

 
To create this event simply click on the checkbox in design mode and you will get the following

Private Sub CheckBoxTerms_Click()

End Sub

 
The following code shows an example of how we use it

' https://excelmacromastery.com/
Private Sub CheckBoxTerms_Click()
 
    If checkboxTerms.Value = True Then
       buttonOk.Enabled = True
    Else
       buttonOk.Enabled = False
    End If
 
End Sub

The Label

The Label Cheat Sheet

Function Operation Example
Text GetSet the text textbox1.Text = «Apple»

The label is the most simple control. Generally speaking, we don’t refer to it in the code. It is used to label the controls or display a short notice.

Setting the Label Text

You can set the text of the Label in the code using the Caption property

LabelAddress.Caption = "Customer Address"

The TextBox

The TextBox Cheat Sheet

Function Operation Example
Text Set the text textbox1.Text = «Apple»
Text Get the text sFruit = textbox1.Text
Value Set the text textbox1.Value = «Apple»
Value Get the text sFruit = textbox1.Value

Setting the Textbox Text

The textbox is used to allows the user to enter text. We can read or write from a text box as follows

TextBoxNotes.Value = "It was the best of times."

sNotes = TextBoxNotes.Value

 
The textbox has properties Text and Values. These are the same thing.

From MSDN: For a TextBox, any value you assign to the Text property is also assigned to the Value property.

 
The problem with the text box is that the user can enter anything. If the user is entering basic text then this is fine. If the text is to be used for a calculation or for looking up something then we need to validate it.

For example, if the user is going to pick a year between 2010 and 2019 we should use a ComboBox/Listbox that only contains valid years. Then we don’t need to validate the format and range of the user’s entry.

Making a TextBox numeric only

The following code prevents the user entering anything other than a number in the textbox

' https://excelmacromastery.com/
Private Sub textboxComments_KeyPress( _
            ByVal KeyAscii As MSForms.ReturnInteger)
         
    Select Case KeyAscii
        Case Is < vbKey0, Is > vbKey9
            KeyAscii = 0
            Beep
    End Select
         
End Sub

Using a Date Control

If you the user to select a date you can use the MonthView control. It is one of the additional controls that comes with Visual Basic. It works quite well and looks like the standard date picker you see in most applications.

To add the MonthView control:

  1. Go the the Visual Basic editor and make sure the Toolbox is visible(View->Toolbox if it’s not visible).
  2. Select Tools and then Additional Controls from the menu.
  3. Place a check on Microsoft MonthView Control, Version 6.0.
  4. The MonthView control will now appear on the Toolbox.

 
To get the user selection from the MonthView control you can use the DateClick event as the following code shows

' https://excelmacromastery.com/
Private Sub MonthView1_DateClick( _	 	 
     ByVal DateClicked As Date)	 	 
 	 	 
    ' Store date in textbox	 	 
    TextBox1.Value = MonthView1.Value	 	 
 	 	 
End Sub	 	 

 
For more information on the MonthView see these links:

Issues adding the MonthView – see top answer on this StackOverflow page

MSDN – Using the MonthView Control

The ComboBox

The ComboBox Cheat Sheet

Function Operation Example
AddItem Add an item listbox.AddItem «Spain»
Clear Remove all Items combo.Clear
List Add a range of items combo.List = Range(«A1»).Value
ListCount Get the number of items cnt = combo.ListCount
ListIndex Get/set selected item Idx = combo.ListIndex
combo.ListIndex = 0
ListRows Get/set number of items displayed NoItems = combo.ListRows
combo.ListRows = 12
RemoveItem Remove an item combo.RemoveItem 1
Value Get the value of selected Item Dim sCountry As String
sCountry = combo.Value

 
The ComboBox is used to allow the user to select an item from a list. It is very similar to the listbox. The main difference is the listbox allows multiple selections.

In most cases we want to do four things with the ComboBoxListBox

  1. Fill it with data when the Form is loaded
  2. Preselect an item.
  3. Retrieve the currently selected item(s).
  4. Perfom an action when the user selects a different item.

Filling the Combobox with data

We can fill the combobox one item at at a time using the AddItem property.

comboBoxFruit.AddItem "Apple"
comboBoxFruit.AddItem "Pear"

 
You would normally use AddItem in a loop where you are checking each item before adding it

Dim cell As Range
' Fill items with first letter is A
For Each cell In Sheet1.Range("A1:A50")
    If Left(cell.Value, 1) = "A" Then
        comboBoxFruit.AddItem cell.Value
    End If
Next

Filling the ComboBox from a range

If you want to fill the ComboBox from an entire range you can do it in one line of code

comboBoxFruit.List = Sheet1.Range("A1:A5").Value

 
Normally when you fill a ComboBox you want to clear the existing contents first

' Clear any existing item
comboBoxFruit.Clear
' Fill the ComboBox
comboBoxFruit.List = Sheet1.Range("A1:A5").Value

Filling the ComboBox – No duplicates

If our range has multiple entries then we want to avoid adding the same item multiple times. We can do this using a Dictionary

' https://excelmacromastery.com/
Sub TestDuplicates()

    ' clear existing values
    comboBoxFruit.Clear
    
    ' Fill given ComboBox from given range ignoring duplicates
    FillComboNoDuplicates comboBoxFruit, Sheet1.Range("A1:A10")
    
End Sub

Sub FillComboNoDuplicates(cbo As ComboBox, rg As Range)
    
    ' Create dictionary
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
    Dim cell As Range, sItem As String
    ' Go through each item in range
    For Each cell In rg
        sItem = Trim(cell.Value)
        ' check if item already exists in dictionary
        If dict.Exists(sItem) = False Then
            ' If doesn't exist then add to dictionary and combobox
            dict.Add sItem, 1
            cbo.AddItem sItem
        End If
    Next
    
    ' Clean up dictonary as we no longer need it
    Set dict = Nothing

End Sub

VBA ComboBox – Full Example 1

The easiest way to show how these work is with an example. Imagine we have a list of countries and their capitals in cells A1:B196.

 
VBA Combobox

 
We want the user to select any country. When they do our UserForm will display the capital of that country. The screenshot below shows and example of this

 
VBA Combobox

 
The first thing we want to do is fill the countries ComboBox when the form loads. We do this using the UserForm_Initialize event which we looked at in the first post on VBA UserForms.

Private Sub UserForm_Initialize()
    
End Sub

 
We can use the following code to fill the ComboBox from a range and set the selected item to be the first one. (Note we don’t need to clear the ComboBox here as the Initialize event is only used once – when the UserForm is created.)

' https://excelmacromastery.com/
Private Sub UserForm_Initialize()
    
    ' Add array to combobox
    ComboBoxCountry.List = Sheet1.Range("A1:A196").Value
    
    ' Set the first item in combobox
    ComboBoxCountry.ListIndex = 0
    
End Sub

 
When the user selects a country we want to display the capital city in the textbox. We use the Change Event of the ComboBox. To create this we simply double-click on the ComboBox and it will be automatically created.

' https://excelmacromastery.com/
Private Sub ComboBoxCountry_Change()
    
    ' Get the value from the combo box
    Dim sCountry As String
    sCountry = ComboBoxCountry.Value
    
    ' Get the range
    Dim rg As Range
    Set rg = Sheet1.Range("A1:B196")
    
    ' Use VLookup to find the capital of the country
    TextBoxCapital.Value = _
        WorksheetFunction.VLookup(sCountry, rg, 2)
    
End Sub

 
When the user clicks Ok we write the selected values to the Results worksheet

' https://excelmacromastery.com/
Private Sub buttonOK_Click()
    
    With shResult

        ' Write the country the was selected
        .Range("A1") = ComboBoxCountry.Value
        
        ' Write the postion of the selected country
        .Range("A3") = ComboBoxCountry.ListIndex

        ' Write the capital of the country
        .Range("A2") = TextBoxCapital.Value

    End With

    ' Close the form
    Unload Me
    
End Sub

VBA ComboBox – Full Example 2

A very commmon task to perform is to update a second ComboBox based on the selection of the first.

 
VBA Controls

 
Imagine we have two ComboBoxes – one contains the name of a country and one has a list of three cities from that country.

 
VBA Combobox Cities

 
When the user selects a country we update the city ComboBox with the cities from that country.

 
Our data is stored as follows

VBA Combobox City

 
Anytime the Country ComboBox value is set to a country we update the City ComboBox to contain the three cities from that country. This happens in two places

  1. When we load the country combo box – the Initialize Event
  2. When the user selects a country – the Change Event

 
The code for these is as follows

' https://excelmacromastery.com/
Private Sub UserForm_Initialize()
    
    ' Add array to combobox
    ComboBoxCountry.List = shCity.Range("A2:A5").Value
    ComboBoxCountry.ListIndex = 0
    
    ' Fill the city ComboBox
    FillCityCombo ComboBoxCountry.ListIndex
    
End Sub

Private Sub ComboBoxCountry_Change()
    ' Fill the city ComboBox
    FillCityCombo ComboBoxCountry.ListIndex
End Sub

 
In both cases we call our FillCityCombo Sub to fill the city ComboBox. It takes one parameter which is the position of the current country selection.

We use the position value to count from the top row of our worksheet range.

' https://excelmacromastery.com/
Sub FillCityCombo(ByVal row As Long)

    ' Get the city range from the given row
    Dim rgCities As Range
    Set rgCities = shCity.Range("B2:D2").Offset(row)
    
    ' Clear current city list
    ComboBoxCity.Clear
    
    ' We transpose the range of columns e.g. B2:D2 to rows so 
    ' we can add to the ComboBox
    ComboBoxCity.List = _
            WorksheetFunction.Transpose(rgCities)
            
    ' Set the first city in list
    ComboBoxCity.ListIndex = 0

End Sub

The ListBox

The ListBox is used in almost the same way as the ComboBox. The code in the ComboBox section above will work for the ListBox also.

The ListBox Cheat Sheet

Function Operation Example
AddItem Add an item listbox.AddItem «Spain»
Clear Remove all Items listbox.Clear
ColumnCount Set the number of visible columns ComboBox1.ColumnCount = 2
ColumnHeads Make the column row visible ComboBox1.ColumnHeads = True
List Range to Listbox
ListBox to Range
Listbox.List = Range(«A1:A4»).Value
Range(«A1:A4»).Value = Listbox.List
List Update a column value Listbox.List(1,2) = «New value»
ListCount Get the number of items cnt = listbox.ListCount
ListIndex Get/set selected item Idx = listbox.ListIndex
combo.ListIndex = 0
RemoveItem Remove an item listbox.Remove 1
RowSource Add a range of values from a worksheet ComboBox1.RowSource = Sheet1.Range(«A2:B3»).Address
Value Get the value of selected Item Dim sCountry As String
sCountry = listbox.Value

We can use the ListBox the same way as we used the ComboBox. The difference is how they are displayed

  • The ListBox displays a list of available items to select.
  • The ComboBox only displays the selected item. You have to click on the ComboBox to see the other available items.

 
The other major difference between them is that the ListBox allows multiple selections and the ComboBox doesn’t.

 
VBA ListBox multi

 
We can get all the selected items in the ListBox by reading through all the items and checking if each one is selected. In the code below we add all the selected items to a Collection.

' USERFROM CODE
' https://excelmacromastery.com/
Private m_CollCountries As Collection

' OK click event
Private Sub buttonOk_Click()
    ' Get the user selections
    Set m_CollCountries = GetSelections
    ' Hide the UserForm
    Hide
End Sub

' Returns the collection of countries
Property Get Countries() As Collection
    Set Countries = m_CollCountries
End Property

' Get the selections from the ListBox
Private Function GetSelections() As Collection
    
    Dim collCountries As New Collection
    Dim i As Long
    
    ' Go through each item in the listbox
    For i = 0 To ListBoxCountry.ListCount - 1
        ' Check if item at position i is selected
        If ListBoxCountry.Selected(i) Then
            ' Add item to our collection
            collCountries.Add ListBoxCountry.List(i)
        End If
    Next i
    
    Set GetSelections = collCountries
    
End Function
' MAIN PROCEDURE CODE
' https://excelmacromastery.com/
' Sub to display the UserForm
Sub DisplayMultiCountry()
    
    Dim frm As New UserFormCountryMulti
    frm.Show

    ' Print the collection
    PrintCollection frm.Countries
    
End Sub

' Sub used to print a collection to the Immediate Window(Ctrl + G)
Public Sub PrintCollection(ByRef coll As Collection)
    
    Debug.Print "The user selected the following countries:"
    Dim v As Variant
    For Each v In coll
        Debug.Print v
    Next
    
End Sub

 
That concludes the two posts on UserForm(see first one here).

I hope you found them of benefit. If you have any questions or queries please feel free to add a comment or email me at Paul@ExcelMacroMastery.com.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Понравилась статья? Поделить с друзьями:
  • Vba excel check if sheet exist
  • Vba excel cells формат
  • Vba excel cells строка столбец
  • Vba excel cells или range
  • Vba excel cells диапазон ячеек