Перейти к основному содержанию

Как сделать, чтобы в группе флажков в Excel был выбран только один флажок?

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

Установите только один флажок с кодом VBA


Установите только один флажок с кодом VBA

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

1. Во-первых, установите нужные флажки. Здесь вы должны вставить Флажки управления ActiveX как показано на следующем скриншоте:

2. Затем нажмите другой + Клавиши F11 одновременно, чтобы открыть Microsoft Visual Basic для приложений окно.

3. В дебюте Microsoft Visual Basic для приложений окна, нажмите Вставить > Модуль класса.

4. Измените название класса на КлсЧк в (Фамилия) коробка Объекты панель, а затем скопируйте и вставьте приведенный ниже код VBA в соответствующий Code окно. Смотрите скриншот:

Код VBA 1: устанавливайте только один флажок за раз

Option Explicit
Public WithEvents Chk As MSForms.CheckBox
Private Sub Chk_Click()
Call SelOneCheckBox(Chk)
End Sub

Sub SelOneCheckBox(Target As Object)
Dim xObj As Object
Dim I As String
Dim n As Integer
If Target.Object.Value = True Then

    I = Right(Target.Name, Len(Target.Name) - 8)
    For n = 1 To ActiveSheet.OLEObjects.Count
      If n <> Int(I) Then
        Set xObj = ActiveSheet.OLEObjects.Item(n)
        xObj.Object.Value = False
        xObj.Object.Enabled = False
      End If
    Next
Else
    I = Right(Target.Name, Len(Target.Name) - 8)
    For n = 1 To ActiveSheet.OLEObjects.Count
      If n <> Int(I) Then
        Set xObj = ActiveSheet.OLEObjects.Item(n)
        xObj.Object.Enabled = True
      End If
    Next
End If
End Sub

5. Теперь щелкните Вставить > Модули, затем скопируйте и вставьте приведенный ниже код VBA в Модули окно.

Код VBA 2: устанавливайте только один флажок за раз

Dim xCollection As New Collection
Public Sub ClsChk_Init()
Dim xSht As Worksheet
Dim xObj As Object
Dim xChk As ClsChk
   Set xSht = ActiveSheet
   Set xCollection = Nothing
    For Each xObj In xSht.OLEObjects
        If xObj.Name Like "CheckBox**" Then
            Set xChk = New ClsChk
            Set xChk.Chk = CallByName(xSht, xObj.Name, VbGet)
            xCollection.Add xChk
        End If
    Next
    Set xChk = Nothing
End Sub

6. нажмите F5 ключ для запуска кода.

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

Внимание: Если новый флажок добавлен в группу флажков, повторно запустите код VBA, чтобы снова активировать все флажки. При удалении флажка из группы флажков также необходимо перезапустить код.


Rприподнятые статьи:

Лучшие инструменты для офисной работы

🤖 Kutools AI Помощник: Революционный анализ данных на основе: Интеллектуальное исполнение   |  Генерировать код  |  Создание пользовательских формул  |  Анализ данных и создание диаграмм  |  Вызов функций Kutools...
Популярные опции: Найдите, выделите или определите дубликаты   |  Удалить пустые строки   |  Объедините столбцы или ячейки без потери данных   |   Раунд без формулы ...
Супер поиск: Множественный критерий VLookup    VLookup с несколькими значениями  |   VLookup по нескольким листам   |   Нечеткий поиск ....
Расширенный раскрывающийся список: Быстрое создание раскрывающегося списка   |  Зависимый раскрывающийся список   |  Выпадающий список с множественным выбором ....
Менеджер столбцов: Добавить определенное количество столбцов  |  Переместить столбцы  |  Переключить статус видимости скрытых столбцов  |  Сравнить диапазоны и столбцы ...
Рекомендуемые функции: Сетка Фокус   |  Просмотр дизайна   |   Большой Формулный Бар    Менеджер книг и листов   |  Библиотека ресурсов (Авто текст)   |  Выбор даты   |  Комбинировать листы   |  Шифровать/дешифровать ячейки    Отправлять электронные письма по списку   |  Суперфильтр   |   Специальный фильтр (фильтровать жирным шрифтом/курсивом/зачеркиванием...) ...
15 лучших наборов инструментов12 Текст Инструменты (Добавить текст, Удалить символы, ...)   |   50+ График Тип (Диаграмма Ганта, ...)   |   40+ Практических Формулы (Рассчитать возраст по дню рождения, ...)   |   19 Вносимые Инструменты (Вставить QR-код, Вставить изображение из пути, ...)   |   12 Конверсия Инструменты (Числа в слова, Конверсия валюты, ...)   |   7 Слияние и разделение Инструменты (Расширенные ряды комбинирования, Разделить клетки, ...)   |   ... и более

Улучшите свои навыки работы с Excel с помощью Kutools for Excel и почувствуйте эффективность, как никогда раньше. Kutools for Excel предлагает более 300 расширенных функций для повышения производительности и экономии времени.  Нажмите здесь, чтобы получить функцию, которая вам нужна больше всего...

Описание


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Comments (14)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Bonjour, Merci pour ce tuto tout fonctionne. Cependant, je suis obligé d'éxécuter manuellement le "ClsChk" à chaque fois pour que cela fonctionne, mon fichier est un fichier groupe pour la société, serait-il possible qu'il se lance automatiquement ? Merci d'avance.
This comment was minimized by the moderator on the site
I want to get this feacture just row by row and not entire sheet.How should i fix this code alittle? I am not familiar with vba too much.If can, plz help me.
This comment was minimized by the moderator on the site
Hi Min Ko Ko,
If you want to select only one option row by row, I recommend you to use the combination of Option Button (Form Control) and Group Box (Form Control).
1. Just draw a Group Box in the worksheet.
2. Keep the Group Box selected, and then draw Option Buttons inside the box.
3. Repeat the steps to insert new Group box and Option Buttons in a new row.
4. As the group box has title and borders, you can apply the below VBA code in the Module code window to hide all titles and borders of group boxes in current worksheet.
<div data-tag="code">Sub ToggleVisible()
Dim myGB As GroupBox
For Each myGB In ActiveSheet.GroupBoxes
myGB.Visible = False
Next myGB
End Sub
This comment was minimized by the moderator on the site
You really need to explain how to access the class name in order to change it. BTW folks, it's F4 to open the window on the left side of the screen and then edit the class name.
This comment was minimized by the moderator on the site
hi,
the error appears under the first code.
xObj.Object.Value = False
This comment was minimized by the moderator on the site
Hi Arnold, did you get any prompt box? and which Excel version are you using?
This comment was minimized by the moderator on the site
It works fine if all you are using is checkboxes.
If you add any other activeX items and assign controls to them, it throws the error Arnold mentioned.
This comment was minimized by the moderator on the site
when i close the Excel and open the file again the checkboxes stop working how do I fix this pls?
This comment was minimized by the moderator on the site
Hi,
Please save the workbook as an Excel Macro-enabled Workbook in order to save the codes in workbook. But when you reopen the workbook, you need to get into the code window to manually run the code in the Module window to activate it.
This comment was minimized by the moderator on the site
Hi, is there a way around? I would like to use this for multiple people, and I am sure they will not run the code aftre opening....
This comment was minimized by the moderator on the site
Bonjour, Je suis dans la même situation. Est-il possible que le module de classe "ClsChk" se lance automatiquement au démarrage ? 
This comment was minimized by the moderator on the site
Hi, I have the same questionIs there any option to open the Excel with the function working?
This comment was minimized by the moderator on the site
Hi,Sorry for the trouble. You can follow the steps below to solve the problem.1. Save the workbook as an Excel Macro-enabled Workbook (Click File > Save as > select a destination folder > select "Excel Macro-Enabled Workbook" in the Save as type drop-down list > Save);2. Add the following code into the ThisWorkbook code editor as shown in the screenshot below.;3. Save the code.<div data-tag="code">Private Sub Workbook_Open()
On Error Resume Next
ClsChk_Init
End Sub

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
On Error Resume Next
ClsChk_Init
End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
On Error Resume Next
ClsChk_Init
End Sub
This comment was minimized by the moderator on the site
Hi! Thanks for this useful guide! I have an additional question: Im working with both columns and rows. If one checkbox value is true, all checkboxes in the same row and column has to be disabled. How do I do that? Best, Morten
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations