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

Как создать раскрывающийся список с несколькими флажками в Excel?

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

Используйте поле списка для создания раскрывающегося списка с несколькими флажками
A: Создайте список с исходными данными
B: Назовите ячейку, в которой вы будете размещать выбранные элементы
C: вставить форму, чтобы помочь вывести выбранные элементы
Легко создавайте раскрывающийся список с флажками с помощью замечательного инструмента
Дополнительные руководства для раскрывающегося списка ...


Используйте поле списка для создания раскрывающегося списка с несколькими флажками

Как показано на скриншоте ниже, на текущем листе все имена в диапазоне A2: A11 будут исходными данными для списка. При нажатии на кнопку в ячейке C4 можно вывести выбранные элементы, и все выбранные элементы в списке будут отображаться в ячейке E4. Для этого сделайте следующее.

A. Создайте список с исходными данными

1. Нажмите Застройщик > Вставить > Список (Active X Control). Смотрите скриншот:

2. Нарисуйте список на текущем листе, щелкните его правой кнопкой мыши и выберите Объекты из контекстного меню.

3. в Объекты диалоговое окно необходимо настроить следующим образом.

  • 3.1 В СписокЗаполнитьДиапазон введите диапазон источников, который будет отображаться в списке (здесь я ввожу диапазон A2: A11);
  • 3.2 В Стиль списка выберите 1 - вариант стиля fmList;
  • 3.3 В Выбор из нескольких вариантов выберите 1 - fmMultiSelectMulti;
  • 3.4 Закройте Объекты диалоговое окно. Смотрите скриншот:

B: Назовите ячейку, в которой вы будете размещать выбранные элементы

Если вам нужно вывести все выбранные элементы в указанную ячейку, например E4, сделайте следующее.

1. Выберите ячейку E4, введите ЛистбоксВывод в Имя Box и нажмите Enter .

C. Вставьте форму, чтобы помочь вывести выбранные элементы

1. Нажмите Вставить > Формы > Прямоугольник. Смотрите скриншот:

2. Нарисуйте прямоугольник на листе (здесь я рисую прямоугольник в ячейке C4). Затем щелкните прямоугольник правой кнопкой мыши и выберите Назначить макрос из контекстного меню.

3. в Назначить макрос диалогового окна, нажмите Новые .

4. В дебюте Microsoft Visual Basic для приложений окна, замените исходный код в Модули окно с приведенным ниже кодом VBA.

Код VBA: создать список с несколькими флажками

Sub Rectangle1_Click()
'Updated by Extendoffice 20200730
Dim xSelShp As Shape, xSelLst As Variant, I, J As Integer
Dim xV As String
Set xSelShp = ActiveSheet.Shapes(Application.Caller)
Set xLstBox = ActiveSheet.ListBox1
If xLstBox.Visible = False Then
    xLstBox.Visible = True
    xSelShp.TextFrame2.TextRange.Characters.Text = "Pickup Options"
    xStr = ""
    xStr = Range("ListBoxOutput").Value
    
    If xStr <> "" Then
         xArr = Split(xStr, ";")
    For I = xLstBox.ListCount - 1 To 0 Step -1
        xV = xLstBox.List(I)
        For J = 0 To UBound(xArr)
            If xArr(J) = xV Then
              xLstBox.Selected(I) = True
              Exit For
            End If
        Next
    Next I
    End If
Else
    xLstBox.Visible = False
    xSelShp.TextFrame2.TextRange.Characters.Text = "Select Options"
    For I = xLstBox.ListCount - 1 To 0 Step -1
        If xLstBox.Selected(I) = True Then
        xSelLst = xLstBox.List(I) & ";" & xSelLst
        End If
    Next I
    If xSelLst <> "" Then
        Range("ListBoxOutput") = Mid(xSelLst, 1, Len(xSelLst) - 1)
    Else
        Range("ListBoxOutput") = ""
    End If
End If
End Sub

Примечание: В коде Прямоугольник1 имя формы; СписокBox1 это имя списка; Выберите параметры и Варианты получения отображаемые тексты фигуры; и ЛистбоксВывод - имя диапазона выходной ячейки. Вы можете изменить их в зависимости от ваших потребностей.

5. Нажмите другой + Q клавиши одновременно, чтобы закрыть Microsoft Visual Basic для приложений окно.

6. Нажмите кнопку прямоугольника, чтобы свернуть или развернуть список. Когда поле списка расширяется, отметьте элементы в поле списка, а затем снова щелкните прямоугольник, чтобы вывести все выбранные элементы в ячейку E4. См. Демонстрацию ниже:

7. Затем сохраните книгу как Книга Excel MacroEnable для повторного использования кода в будущем.


Создавайте раскрывающийся список с флажками с помощью замечательного инструмента

Вышеупомянутый метод слишком многоэтапный, чтобы с ним легко справиться. Здесь очень рекомендую Раскрывающийся список с флажками полезности Kutools для Excel чтобы помочь вам легко создать раскрывающийся список с флажками в указанном диапазоне, текущем листе, текущей книге или всех открытых книгах в зависимости от ваших потребностей. См. Демонстрацию ниже:
Скачайте и попробуйте прямо сейчас! (30-дневный бесплатный пробный период)

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

1. Откройте лист, в котором установлен раскрывающийся список проверки данных, щелкните Кутулс > Раскрывающийся список > Раскрывающийся список с флажками > Настройки. Смотрите скриншот:

2. в Раскрывающийся список с флажками Настройки диалоговое окно, настройте следующим образом.

  • 2.1). Обращаться к в разделе укажите область применения, в которой вы будете создавать флажки для элементов в раскрывающемся списке. Вы можете указать определенный диапазон, текущий рабочий лист, текущая рабочая тетрадь or все открытые книги в зависимости от потребностей.
  • 2.2). режим раздел выберите стиль, в котором вы хотите выводить выбранные элементы;
  • Вот берет Изменить в качестве примера, если вы выберете этот вариант, значение ячейки будет изменено в зависимости от выбранных элементов.
  • 2.3). Разделитель поле введите разделитель, который вы будете использовать для разделения нескольких элементов;
  • 2.4). Направление текста раздел выберите направление текста в зависимости от ваших потребностей;
  • 2.5) Нажмите OK .

3. Последний шаг, нажмите Кутулс > Раскрывающийся список > Раскрывающийся список с флажками > Включить раскрывающийся список флажков чтобы активировать эту функцию.

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

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

  Если вы хотите получить бесплатную (30-дневную) пробную версию этой утилиты, пожалуйста, нажмите, чтобы загрузить это, а затем перейдите к применению операции в соответствии с указанными выше шагами.


Статьи по теме:

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

Создать раскрывающийся список из другой книги в Excel
Создать раскрывающийся список проверки данных среди листов в книге довольно просто. Но если данные списка, необходимые для проверки данных, находятся в другой книге, что вы будете делать? В этом руководстве вы узнаете, как подробно создать раскрывающийся список из другой книги в Excel.

Создайте раскрывающийся список с возможностью поиска в Excel
Для раскрывающегося списка с многочисленными значениями найти подходящий - непростая задача. Ранее мы ввели метод автоматического заполнения раскрывающегося списка при вводе первой буквы в раскрывающемся списке. Помимо функции автозаполнения, вы также можете сделать раскрывающийся список доступным для поиска для повышения эффективности работы при поиске правильных значений в раскрывающемся списке. Чтобы сделать раскрывающийся список доступным для поиска, попробуйте метод, описанный в этом руководстве.

Автоматическое заполнение других ячеек при выборе значений в раскрывающемся списке Excel
Допустим, вы создали раскрывающийся список на основе значений в диапазоне ячеек B8: B14. При выборе любого значения в раскрывающемся списке необходимо, чтобы соответствующие значения в диапазоне ячеек C8: C14 автоматически заполнялись в выбранной ячейке. Для решения проблемы методы, описанные в этом руководстве, окажут вам услугу.

Дополнительные руководства для раскрывающегося списка ...

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

🤖 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 (70)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hello-

This is fabulous, but I was wondering if there is a way to call the code as a subroutine, ie Click Button 1, run this code with X List Box and X Output cell. I want to pass the listbox and the output cell as variables into this code. Any help would be greatly appreciated.

I've tried this:
Private Sub Rectangle1_Click()
Call MultiSelctDropdown(ListBox1,Output1)
End Sub

Private Sub Rectangle2_Click()
Call MultiSelctDropdown(ListBox2,Output2)
End Sub

Private Sub MultiSelectDropdown(ListBox As String, Output As String)
Dim xSelShp As Shape, xSelLst As Variant, I, J As Integer
Dim xV As String
Set xSelShp = ActiveSheet.Shapes(Application.Caller)
Set xLstBox = ActiveSheet.ListBox
If xLstBox.Visible = False Then
xLstBox.Visible = True
xSelShp.TextFrame2.TextRange.Characters.Text = "Enter"
xStr = ""
xStr = Range("Output").Value

If xStr <> "" Then
xArr = Split(xStr, ",")
For I = xLstBox.ListCount - 1 To 0 Step -1
xV = xLstBox.List(I)
For J = 0 To UBound(xArr)
If xArr(J) = xV Then
xLstBox.Selected(I) = True
Exit For
End If
Next
Next I
End If
Else
xLstBox.Visible = False
xSelShp.TextFrame2.TextRange.Characters.Text = "Click Here to Select Products"
For I = xLstBox.ListCount - 1 To 0 Step -1
If xLstBox.Selected(I) = True Then
xSelLst = xLstBox.List(I) & "," & xSelLst
End If
Next I
If xSelLst <> "" Then
Range("Output") = Mid(xSelLst, 1, Len(xSelLst) - 1)
Else
Range("Output") = ""
End If
End If
End Sub
This comment was minimized by the moderator on the site
Ok I figured this one out (see below)

But now I want to have only ONE list box that I can use over and over again with different buttons but different output depending on the button pushed. And the code below works for this EXCEPT the items selected when the list box pops up includes all items that have been outputted from the code.

If list box1 contains

Apples
Oranges
Pears
Kiwi

and button 1 is pressed and Apples is selected, when button 2 is pressed Apples is already selected, and if during button press 2 pears is selected when you go back to button 1 Apples AND Pears are selected.

How can I either clear all selected when a button is pressed OR make the selected options equal to the output.


Private Sub Button1_Click()
Call ProductSelection(ActiveSheet.ListBox1, "Button1Output", 243, 215)
End Sub
Private Sub Button2_Click()
Call ProductSelection(ActiveSheet.ListBox1, "Button2Output", 472, 215)
End Sub



Private Sub ProductSelection(xListBox As Object, Output As String, left As Integer, height As Integer)
Dim xSelShp As Shape, xSelLst As Variant, I, J As Integer
Dim xV As String
Set xSelShp = ActiveSheet.Shapes(Application.Caller)
Set xLstBox = xListBox
If xLstBox.Visible = False Then
xLstBox.Visible = True
xLstBox.left = left
xLstBox.height = height
xSelShp.TextFrame2.TextRange.Characters.Text = "Enter"
xStr = ""
xStr = Range(Output).Value

If xStr <> "" Then
xArr = Split(xStr, ",")
For I = xLstBox.ListCount - 1 To 0 Step -1
xV = xLstBox.List(I)
For J = 0 To UBound(xArr)
If xArr(J) = xV Then
xLstBox.Selected(I) = True
Exit For
End If
Next
Next I
End If
Else
xLstBox.Visible = False
xSelShp.TextFrame2.TextRange.Characters.Text = "Click Here to Select Products"
For I = xLstBox.ListCount - 1 To 0 Step -1
If xLstBox.Selected(I) = True Then
xSelLst = xLstBox.List(I) & "," & xSelLst
End If
Next I
If xSelLst <> "" Then
Range(Output) = Mid(xSelLst, 1, Len(xSelLst) - 1)
Else
Range(Output) = ""
End If
End If
End Sub
This comment was minimized by the moderator on the site
Hi there- this is super helpful, thank you! Can you tell me how I can draw a list box based on a list in a different worksheet (but same file)? I've tried entering my worksheet name (i.e., 'lists') followed by the range in the list fill range (after clicking on Properties) but this does not work.Thanks!
This comment was minimized by the moderator on the site
Hi Meghan,Supposing you want to <span style="letter-spacing: 0.2px; color: inherit; font-family: inherit; font-style: inherit; font-variant-ligatures: inherit; font-variant-caps: inherit;">ListBox1</span><span style="letter-spacing: 0.2px; color: inherit; font-family: inherit; font-style: inherit; font-variant-ligatures: inherit; font-variant-caps: inherit;">Sheet1</span><div data-tag="code">Sub listboxlistfillrangefromdifferentsheet()
Sheet1.ListBox1.ListFillRange = Sheet2.Range("A2:A20").Address(, , , True)
End Sub
This comment was minimized by the moderator on the site
hello, I have a problem with the list box: to make the list going down, I have to click on the box that allows the list to go down but when I click, it does not go down automatically, I have to click outside the list so that it refreshes and the list goes down, what to do? Thank you
This comment was minimized by the moderator on the site
Hi,You can't scroll ActiveX Listbox by mouse wheel. There is no setting for it.

This comment was minimized by the moderator on the site
Hi, thank you for sharing this! I have a question though, is it possible to populate different cells based on the selected option?For example, instead of having everything in one cell, each selection is populated in the cell below the earlier selection. Thank you!
This comment was minimized by the moderator on the site
Hi faez,
The VBA below helps to populate the selected options in different cells on the same row. Please have a try.

Sub Rectangle2_Click()
'Updated by Extendoffice 20211124
Dim xSelShp As Shape, xSelLst As Variant, I As Integer
Dim xRg As Range
Set xSelShp = ActiveSheet.Shapes(Application.Caller)
Set xLstBox = ActiveSheet.ListBox1
If xLstBox.Visible = False Then
xLstBox.Visible = True
xSelShp.TextFrame2.TextRange.Characters.Text = "Pickup Options"
Else
xLstBox.Visible = False
xSelShp.TextFrame2.TextRange.Characters.Text = "Select Options"
Set xRg = Range("ListBoxOutput")
For I = 0 To xLstBox.ListCount - 1
If xLstBox.Selected(I) = True Then
xSelLst = xLstBox.List(I)
xRg.Value = Mid(xSelLst, 1, Len(xSelLst))
Set xRg = xRg.Offset(0, 1)
End If
Next I
End If
End Sub
This comment was minimized by the moderator on the site
Hi Crystal,
Thanks a lot for this code, very helpful and convenient. One question : how to adpat it in order not to have the separator ";" if only one item is selected ?
This comment was minimized by the moderator on the site
Hi Eloi,No separator is displayed when you select only one item in the list.
This comment was minimized by the moderator on the site
Thanks Crystal, the mistake was in my adaptation of the code.
If someone needs to adapt it with a click on a cell instead of a click on a shape, you could try this (with a call to this sub in your sheet, with a condition when your cell is selected)

Sub affichage_liste(xLstBox As MSForms.ListBox, texte1 As String)
'Updated by Extendoffice 20200730
Dim xSelLst As Variant, I, J As Integer
Dim xV As String

If xLstBox.Visible = False Then
xLstBox.Visible = True
xStr = ""
xStr = Range(texte1).Value

If xStr <> "" Then
xArr = Split(xStr, ";")
For I = xLstBox.ListCount - 1 To 0 Step -1
xV = xLstBox.List(I)
For J = 0 To UBound(xArr)
If xArr(J) = xV Then
xLstBox.Selected(I) = True
Exit For
End If
Next
Next I
End If
Else
xLstBox.Visible = False
For I = xLstBox.ListCount - 1 To 0 Step -1
If xLstBox.Selected(I) = True Then
xSelLst = xLstBox.List(I) & "; " & xSelLst
End If
Next I
If xSelLst <> "" Then
Range(texte1) = Mid(xSelLst, 1, Len(xSelLst) - 2)
Else
Range(texte1) = ""
End If
End If
End Sub
This comment was minimized by the moderator on the site
Hi Eloi,The code you provided doesn't seem to work. I have modified it again as below.  After adding the code in your Sheet(Code) window, go back to the worksheet, click the cell C4 to expand the list box, after selecting items from the list box, click on any cell in the worksheet to output the selection, and no separator is displayed when you select only one item in the list.
<div data-tag="code">Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Updated by Extendoffice 20211223
Dim xSelLst As Variant, I, J As Integer
Dim xV As String
Set xLstBox = ActiveSheet.ListBox1

If Target.Address = "$C$4" Then


If xLstBox.Visible = False Then
xLstBox.Visible = True
xStr = ""
xStr = Range("ListBoxOutput").Value

If xStr <> "" Then
xArr = Split(xStr, ";")
For I = xLstBox.ListCount - 1 To 0 Step -1
xV = xLstBox.List(I)
For J = 0 To UBound(xArr)
If xArr(J) = xV Then
xLstBox.Selected(I) = True
Exit For
End If
Next
Next I
End If

End If

Else
xLstBox.Visible = False

For I = xLstBox.ListCount - 1 To 0 Step -1
If xLstBox.Selected(I) = True Then
xSelLst = xLstBox.List(I) & "; " & xSelLst
End If
Next I
If xSelLst <> "" Then
Range("ListBoxOutput") = Mid(xSelLst, 1, Len(xSelLst) - 2)
Else
Range("ListBoxOutput") = ""
End If


End If

End Sub
This comment was minimized by the moderator on the site
Thanks a lot Crystal
This comment was minimized by the moderator on the site
Bonjour,Je suis plus que novice sur excel étant sur mac je ne peux utiliser l'outil Kutools j'ai donc tenté de créer une liste déroulante où l'on peut cocher plusieurs items mais je bloque dès le début dans l'onglet développeur puisque je n'ai pas du tout l'outil "insert".Merci pour votre aide
This comment was minimized by the moderator on the site
Hi I am newbie to VBA. I tried to execute the code but i get the following error "Run-time error '-2147024809 (80070057)': The Item with the specified name wasn't found". Can you help me with this
This comment was minimized by the moderator on the site
Hi Gowtham,It seem that this error occurs when you running the code directly in the Code editor (the Microsoft Visual Basic for Applications window).After adding the code, please press the Alt + Q keys to close the Microsoft Visual Basic for Applications window. Go back to the worksheet and execute the code by clicking the rectangle button (see the .gif picture in step 6).
This comment was minimized by the moderator on the site
Hi Crystal, even after your tip am getting same error as Gowtham. My error is right after protect my sheet. Would you please help me with this issue?
This comment was minimized by the moderator on the site
Hi Crystal, Even After your tip I am getting same error as Gowtham.
This comment was minimized by the moderator on the site
Hi Mina,Which Excel and Windows version are you using?
This comment was minimized by the moderator on the site
Hello,I added this code to an existing macro template and it is loading the selections correctly, but it is NOT clearing out the x on the selected items..This will be used on/in a template worksheet that has submit button/macro to load the worksheet answers into a hidden worksheet with a data table.And am happy to say the field data loaded to the cell, transferred into my variable, and loaded to the data table as expected.
This code was a HUGE blessing!
I use excel 2016
How do I fix this. I am using this version from below.
Sub Rectangle1_Click()
'Updated by Extendoffice 20200730
Dim xSelShp As Shape, xSelLst As Variant, I, J As Integer
Dim xV As String
Set xSelShp = ActiveSheet.Shapes(Application.Caller)
Set xLstBox = ActiveSheet.ListBox1
If xLstBox.Visible = False Then
xLstBox.Visible = True
xSelShp.TextFrame2.TextRange.Characters.Text = "Pickup Options"
xStr = ""
xStr = Range("ListBoxOutput").Value

If xStr <> "" Then
xArr = Split(xStr, ";")
For I = xLstBox.ListCount - 1 To 0 Step -1
xV = xLstBox.List(I)
For J = 0 To UBound(xArr)
If xArr(J) = xV Then
xLstBox.Selected(I) = True
Exit For
End If
Next
Next I
End If
Else
xLstBox.Visible = False
xSelShp.TextFrame2.TextRange.Characters.Text = "Select Options"
For I = xLstBox.ListCount - 1 To 0 Step -1
If xLstBox.Selected(I) = True Then
xSelLst = xLstBox.List(I) & ";" & xSelLst
End If
Next I
If xSelLst <> "" Then
Range("ListBoxOutput") = Mid(xSelLst, 1, Len(xSelLst) - 1)
Else
Range("ListBoxOutput") = ""
End If
End If
End Sub
This comment was minimized by the moderator on the site
Hello,

I'm having a similar problem to Tom from 2 months ago. When I try to share my file with a colleague, the multi-select droplist list isn't working. However, I used the Kutools add-on to create this as opposed to creating it myself. I've also saved it as macro-enabled.
This comment was minimized by the moderator on the site
Hi ben,The multi-select drop down list feature of Kutools only works in the Excel that installed our Kutools. We are working on this issue, sorry for the inconvenience.
This comment was minimized by the moderator on the site
Hello I looking the resolve for problem with saving choosing on drop down list

when i choose something on list and send file to my colleague, then when he open file and want to check my list then list has cleared and cell "ListBoxOutput" was cleared too.

help please :)
This comment was minimized by the moderator on the site
Hi Tom,
Please save the workbook as an "Excel MacroEnable Workbook" and then send this .xlsm file to your colleague.
This comment was minimized by the moderator on the site
hello i save this file in this format from beginning ;), but without effect. still when i fill file and send to someone then when he opened file and click to "shape" then macro started from begin and cleared list
This comment was minimized by the moderator on the site
Hi Tom,
I am sorry for the mistake. The code has been updated again. Please have a try.

Sub Rectangle1_Click()

'Updated by Extendoffice 20200730

Dim xSelShp As Shape, xSelLst As Variant, I, J As Integer

Dim xV As String

Set xSelShp = ActiveSheet.Shapes(Application.Caller)

Set xLstBox = ActiveSheet.ListBox1

If xLstBox.Visible = False Then

xLstBox.Visible = True

xSelShp.TextFrame2.TextRange.Characters.Text = "Pickup Options"

xStr = ""

xStr = Range("ListBoxOutput").Value



If xStr <> "" Then

xArr = Split(xStr, ";")

For I = xLstBox.ListCount - 1 To 0 Step -1

xV = xLstBox.List(I)

For J = 0 To UBound(xArr)

If xArr(J) = xV Then

xLstBox.Selected(I) = True

Exit For

End If

Next

Next I

End If

Else

xLstBox.Visible = False

xSelShp.TextFrame2.TextRange.Characters.Text = "Select Options"

For I = xLstBox.ListCount - 1 To 0 Step -1

If xLstBox.Selected(I) = True Then

xSelLst = xLstBox.List(I) & ";" & xSelLst

End If

Next I

If xSelLst <> "" Then

Range("ListBoxOutput") = Mid(xSelLst, 1, Len(xSelLst) - 1)

Else

Range("ListBoxOutput") = ""

End If

End If

End Sub
This comment was minimized by the moderator on the site
Now it's working perfectly.

Many thanks for your help
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations