Vba excel очистить комбобокс

How can I programmatically remove all items from a combobox in VBA?

asked Jun 8, 2010 at 14:22

sooprise's user avatar

Psuedo code ahead (updated with actual code):

Do While ComboBox1.ListCount > 0
    ComboBox1.RemoveItem (0)
Loop

Basically, while you have items, remove the first item from the combobox. Once all the items have been removed (count = 0), your box is blank.

Method 2: Even better

ComboBox1.Clear

answered Jun 8, 2010 at 14:27

Tommy's user avatar

TommyTommy

39.4k10 gold badges89 silver badges120 bronze badges

4

You need to remove each one individually unfortunately:

       For i = 1 To ListBox1.ListCount

           'Remove an item from the ListBox using ListBox1.RemoveItem 
       Next i

Update — I don’t know why my answer did not include the full solution:

For i = ListBox1.ListCount - 1 to 0 Step - 1 
        ListBox1.RemoveItem i 
Next i 

answered Jun 8, 2010 at 14:29

Robben_Ford_Fan_boy's user avatar

3

The simplest way:

Combobox1.RowSource = ""  'Clear the list
Combobox1.Clear           'Clear the selected text

answered Mar 9, 2015 at 21:42

Hendry Halim's user avatar

0

You can use the ControlFormat method:

ComboBox1.ControlFormat.RemoveAllItems

Mifeet's user avatar

Mifeet

12.7k5 gold badges58 silver badges107 bronze badges

answered Aug 24, 2015 at 19:16

David's user avatar

DavidDavid

611 silver badge2 bronze badges

0

Best Way:

Combobox1.items.clear();

Taryn's user avatar

Taryn

241k56 gold badges362 silver badges405 bronze badges

answered Jul 18, 2012 at 15:17

Mr_Hmp's user avatar

Mr_HmpMr_Hmp

2,4342 gold badges35 silver badges53 bronze badges

0

For Access VBA, if a ComboBox has been populated with a Row Source Type of Value List, I find the following works:

ComboBox.RowSource = ""

answered Jun 15, 2020 at 18:33

Lars49's user avatar

For Access VBA, which does not provide a .clear method on user form comboboxes, this solution works flawlessly for me:

   If cbxCombobox.ListCount > 0 Then
        For remloop = (cbxCombobox.ListCount - 1) To 0 Step -1
            cbxCombobox.RemoveItem (remloop)
        Next remloop
   End If

answered Feb 24, 2016 at 13:46

Tim Wray's user avatar

1

In Access 2013 I’ve just tested this:

While ComboBox1.ListCount > 0
    ComboBox1.RemoveItem 0
Wend

Interestingly, if you set the item list in Properties, this is not lost when you exit Form View and go back to Design View.

answered Feb 17, 2016 at 10:46

Pat Harkin's user avatar

me.Combobox1.Clear

This is the common method

answered Aug 8, 2016 at 6:43

Henning Lee's user avatar

Henning LeeHenning Lee

5344 silver badges12 bronze badges

I could not get clear to work. (Mac Excel)
but this does.

ActiveSheet.DropDowns(«CollectionComboBox»).RemoveAllItems

answered Mar 9, 2020 at 8:13

Andrew Watkins's user avatar

If you want to simply remove the value in the combo box:

me.combobox = ""

If you want to remove the recordset of the combobox, the easiest way is:

me.combobox.recordset = ""
me.combobox.requery

Hoppo's user avatar

Hoppo

1,1201 gold badge13 silver badges32 bronze badges

answered Jun 22, 2020 at 23:42

bigjoepro75's user avatar

Private Sub cmdClear_Click()
    ComboBox1.Value = Null
    ComboBox2.Value = Null
End Sub

answered May 17, 2016 at 18:20

Robert's user avatar

0

 

Beginer_78

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

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

Доброго времени суток всем.

 Есть комбо, заполняемый по дате. Требуется его очистить и заполнить новыми объектами при выборе новой даты. Но при нажатии на кнопку «новый выбор» имеем ошибку 381.
 Подскажите, как справиться с проблемой?

 

Юрий М

Модератор

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

Контакты см. в профиле

#2

19.10.2019 10:56:17

Код
CB_Object.Clear
 

Beginer_78

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

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

 

vikttur

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

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

Работает. Нет, не работает. Да ну, все работает…
Так и будем кидаться сообщениями да/нет или покажете, что не работает?

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

 

Юрий М

Модератор

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

Контакты см. в профиле

Beginer_78, у Вас и в коде вопрос, как очистить КомбоБокс Я показал, как правильно его очищать. А ошибка возникает у Вас позже.

 

Beginer_78

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

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

Комрады, извините.
Это именно ужатый вариант и CB_Object.Clear не работает именно в такой конструкции. Потому и выложил пример в таком виде.

 

Юрий М

Модератор

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

Контакты см. в профиле

А что, мой вариант не очищает КомбоБокс?

 

Beginer_78

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

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

#8

19.10.2019 14:07:47

Вы правы. Как оказалось, Ваш вариант работает. Но  итоговая проблема возникновения ошибки не решена.(( Может есть идеи по преодолению проблемы?

Код
    Set Iobject = Range(CB_Object.Column(1)) 

В этой строчке возникает ошибка при нажатии на Cmb_VTZ.

 

Юрий М

Модератор

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

Контакты см. в профиле

Beginer_78, а ведь можно было и не цитировать меня ))
Про «итоговую» проблему Вы в теме ничего не обозначили — только очистка КомбоБокса. Но подумайте сами: Вы сначала очищаете КомбоБокс, а потом переменной Iobject (типа Range) пытаетесь присвоить значение из КомбоБокса. Но ведь там УЖЕ пусто!

 

Beginer_78

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

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

Доброго времени суток всем.
Прошу прощения за паузу, не было времени заниматься данным вопросом….

Подчистил пример.

Юрий М, прошу поясните пжл свою мысль.

Если нажимать кнопку «Новый выбор» при пустом комбо, то ошибки нет. В случае же заполненного по какой-либо дате из списка, выпрыгивает ошибка 381. Сould not get the column property. invalid property array index

Моему опыту не достает понимания, как с ней справиться…

 

Юрий М

Модератор

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

Контакты см. в профиле

#11

30.10.2019 14:32:47

Цитата
Beginer_78 написал:
Подчистил пример

Перестарались: КомбоБокс не заполняется.

 

Beginer_78

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

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

По датам, которые вносятся вручную из списка?

 

Юрий М

Модератор

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

Контакты см. в профиле

Я не знаю, что и как должно заполняться: Вы же ничего об этом не говорите.
И перечитайте название этой темы: «Как очистить ComboBox«. Ответ дан ещё в #2. ComboBox Очищается?  Всё — вопрос исчерпан.
Если появились ДРУГИЕ вопросы — это в новой теме.

 

Beginer_78

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

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

#14

30.10.2019 14:50:32

ОК.

Добрый день.
В VBA новичек, прошу помощи. Есть макрос для заполyения Combobox:

[vba]

Код

Private Sub dobav_VMRP_ob()
For Each c In Worksheets(2).Range(«A4:A44»)
If VarType(c) <> vbEmpty Then Лист1.ComboBox1.AddItem (c)
Next c
For Each c In Worksheets(2).Range(«L4:L46»)
If VarType(c) <> vbEmpty Then Лист1.ComboBox2.AddItem (c)
Next c
For Each c In Worksheets(2).Range(«B2:H2»)
If VarType(c) <> vbEmpty Then Лист1.ComboBox3.AddItem (c)
Next c
End Sub

[/vba]

Также есть макрос для очистки Combobox:

[vba]

Код

Private Sub ochistka_ob()
For i = 1 To ComboBox1.ListCount
ComboBox1.RemoveItem 0
Next i
For i = 1 To ComboBox2.ListCount
ComboBox2.RemoveItem 0
Next i
For i = 1 To ComboBox3.ListCount
ComboBox3.RemoveItem 0
Next i
End Sub

[/vba]

Дело в том, что в зависимости от условия, данный Combobox будет заполняться разными данными (из разных диапазонов ячеек), перед этом очищаясь.
Первый раз заполняется нормально, но при выборе другого условия, после очистки, он пишет Permissions Denied на строке:

If VarType© <> vbEmpty Then Лист1.ComboBox1.AddItem ©

т.е. при добавлении других элементов в Combobox.

Прошу помощи.
[moder]Оформляйте коды тегами (кнопка #). Исправила[/moder]

Обычно содержимое поля со списком можно очистить, очистив данные списка «Диапазон ввода». Но как насчет очистки содержимого всех полей со списком на листе Excel? В этой статье готовятся два кода VBA, которые помогут вам не только очистить содержимое поля со списком, но также очистить содержимое всех полей со списком одновременно на листе Excel.

Легко очистить содержимое поля со списком с помощью кода VBA


Легко очистить содержимое поля со списком с помощью кода VBA

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

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

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

VBA 1: очистить содержимое поля со списком на листе

Sub ClearAComboBox()
ActiveSheet.Shapes.Range(Array("Drop Down 2")).Select
With Selection
    .ListFillRange = ""
End With
End Sub

Внимание: В коде «Drop Down 2» — это имя поля со списком, из которого вы очистите содержимое. Пожалуйста, измените его на свой собственный.

VBA 2: очистить содержимое всех полей со списком на активном листе

Sub ClearComboBox()
    Dim xOle As OLEObject
    Dim xDrop As DropDown
    Application.ScreenUpdating = False
    For Each xOle In ActiveSheet.OLEObjects
        If TypeName(xOle.Object) = "ComboBox" Then
            xOle.ListFillRange = ""
        End If
    Next
    For Each xDrop In ActiveSheet.DropDowns
        xDrop.ListFillRange = ""
    Next
    Application.ScreenUpdating = True
End Sub

3. нажмите F5 или нажмите кнопку «Выполнить», чтобы запустить код.

Затем вы можете увидеть, что содержимое очищено в указанном поле со списком или во всех полях со списком на активном листе, как показано ниже:

Внимание: коды VBA могут применяться как к полю со списком (элемент управления формой), так и к полю со списком (элемент управления ActiveX).


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

  • Как одновременно очистить содержимое и форматирование в ячейках в Excel?
  • Как очистить содержимое именованного диапазона в Excel?
  • Как очистить ограниченные значения в ячейках в Excel?
  • Как очистить указанное содержимое ячейки при изменении значения другой ячейки в Excel?
  • Как очистить указанное содержимое ячейки при открытии и выходе из книги Excel?

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

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


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

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Комментарии (0)


Оценок пока нет. Оцените первым!

In this Article

  • Create a ComboBox in Excel Worksheet
  • Populate a ComboBox in VBA code
  • Populate a ComboBox from a Cells Range
  • Get a Selected Item of a ComboBox in VBA
  • Clear a ComboBox
  • Use a ComboBox in a Userform

This tutorial will demonstrate how to work with ComboBoxes in VBA.

ComboBoxes allow users to select an option from a drop-down menu list. ComboBoxes can be created in VBA UserForms or with an Excel worksheet. In this tutorial, you will learn how to create and manipulate ComboBoxes in VBA and in Excel worksheets.

If you want to learn how to create a Listbox, click here: VBA Listbox

If you want to learn how to create a Checkbox, click here: VBA Checkbox

Create a ComboBox in Excel Worksheet

In order to insert a ComboBox in the Worksheet, you need to go to the Developer tab, click Insert and under ActiveX Controls choose Combo Box:

vba insert combobox

Image 1. Insert a ComboBox in the Worksheet

When you select the ComboBox which you inserted, you can click on Properties under the Developer tab:

vba combobox properties

Image 2. Change ComboBox Properties

Here you can set different properties of the ComboBox. To start, we changed the attribute Name to cmbComboBox. Now, we can use the ComboBox with this name in VBA code.

Populate a ComboBox in VBA code

First, we need to populate the ComboBox with values. In most cases, a ComboBox needs to be populated when the Workbook is opened. Because of this, we need to put a code for populating the ComboBox in object Workbook, procedure Open. This procedure is executed every time a user opens the Workbook. Here is the code:

With Sheet1.cmbComboBox

    .AddItem "John"
    .AddItem "Michael"
    .AddItem "Jennifer"
    .AddItem "Lilly"
    .AddItem "Robert"

End With

When you click on the drop-down menu, you will get 5 names to choose from (John, Michael, Jennifer, Lilly and Robert):

vba combobox populate

Image 3. Populate the ComboBox in VBA

Populate a ComboBox from a Cells Range

Another possible way to populate a ComboBox is to let a user do it. A ComboBox can be linked to the cells range. In this approach, every time a user enters a new value in the cells range, the ComboBox will update with that value.

If you want to enable this, you have to go to the Properties of the ComboBox and set the attribute ListFillRange to the cells range (in our case E2:E5):

vba populate combobox from cells range

Image 4. Populate the ComboBox from the cells range

We linked our ComboBox with the range E2:E5, where we put names we want (Nathan, Harry, George, Roberta). As a result, the ComboBox is now populated with these names:

vba populated combobox

Image 5. Populated ComboBox from the cells range

Get a Selected Item of a ComboBox in VBA

The purpose of a ComboBox is to get a users choice. In order to retrieve a users choice, you need to use this code:

Dim strSelectedItem As Variant

strSelectedItem = Sheet1.cmbComboBox.Value

The users selection is in the attribute Value of Sheet1.cmbComboBox object. This value is assigned to the variable strSelectedItem:

vba combobox get selected value

Image 6. Get a selected value from the ComboBox in VBA

We selected Julia in the ComboBox and executed the procedure. As you can see in Image 5, the value of the strSelectedItem is Julia, which is the value we selected. Now you can process this variable further in the code.

Clear a ComboBox

If you want to clear a ComboBox in VBA, you need to use Clear method of Sheet1.lstComboBox object. It will delete all the items from the ComboBox. Here is the code:

Sheet1.cmbComboBox.Clear

Notice that the Clear method does not delete the attribute ListFillRange, so it must be removed from the properties of the ComboBox beforehand.

When we execute the code, we get the empty ComboBox:

vba clear combobox

Image 7. Clear the ComboBox

Use a ComboBox in a Userform

As we mentioned, Combobox is most often used in Userforms. To explain how you can do it, we will first insert an Userform. In VBA editor, right-click on Module name, click on Insert and choose UserForm:

vba combobox insert userform

Image 8. Insert a Userform

To display controls for inserting, you need to enable the Toolbox. To do this, click on the Toolbox icon in the toolbar. After that, you will get the windows with all the controls available. You can click on ComboBox to create it in the Userform.

vba combobox insert in userform

Image 9. Insert a ComboBox in the Userform

We will name the ComboBox cmbComboBox. In order to populate it with values, we need to put the following code into the method Initialize of the object UserForm:

Private Sub UserForm_Initialize()

    With UserForm1.cmbComboBox

        .AddItem "John"
        .AddItem "Michael"
        .AddItem "Jennifer"
        .AddItem "Lilly"
        .AddItem "Robert"

    End With

End Sub

This code triggers every time a user runs the Userform and populates the Combobox with these 5 names:

vba combobox in userform

Image 10. The ComboBox with values in the Userform

If you want to get selected value from the ComboBox, you need to use the same logic for the Combobox in a Worksheet, which is explained earlier in the article.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Заполнение ComboBox данными с помощью кода VBA Excel. Добавление значений в поле со списком методом AddItem, из массива и из диапазона рабочего листа. Примеры.

Заполнение ComboBox методом AddItem

Создайте пользовательскую форму UserForm1 и разместите на ней поле со списком ComboBox1. Используйте метод AddItem для заполнения элемента управления значениями:

Sub Test1()

    With UserForm1.ComboBox1

        .AddItem «Кружка»

        .AddItem «Стакан»

        .AddItem «Бокал»

        .AddItem «Пиала»

        .AddItem «Фужер»

    End With

UserForm1.Show

End Sub

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

ComboBox, заполненный значениями методом .AddItem

Для заполнения элемента управления ComboBox значениями из массива будем использовать свойство поля со списком List и функцию Array:

Sub Test2()

    With UserForm1

        .ComboBox1.List = Array(«Кружка», «Стакан», «Бокал», «Пиала», «Фужер»)

        .Show

    End With

End Sub

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

Таким же образом можно использовать не только функцию Array, но и переменную массива, предварительно объявленную и заполненную значениями:

Sub Test3()

    Dim a(4) As String

        a(0) = «Кружка»

        a(1) = «Стакан»

        a(2) = «Бокал»

        a(3) = «Пиала»

        a(4) = «Фужер»

    With UserForm1

        .ComboBox1.List = a

        .Show

    End With

End Sub

Заполнение ComboBox значениями из ячеек

Для заполнения поля со списком значениями из диапазона ячеек рабочего листа будем использовать свойство комбинированного списка RowSource, предварительно заполнив диапазон «A1:A5» активного листа уже известными значениями:

Sub Test4()

    With UserForm1

        .ComboBox1.RowSource = «A1:A5»

        .Show

    End With

End Sub

ComboBox, заполненный значениями из диапазона ячеек

Чтобы присвоить элементу управления ComboBox значения из диапазона ячеек любого рабочего листа, добавьте ссылку на него перед наименованием диапазона, например, замените «A1:A5» на «Лист1!A1:A5», и поле со списком будет заполнено значениями ячеек «A1:A5», расположенных на листе с именем «Лист1». Имя листа берется из наименования ярлыка.

Очистка ComboBox от значений

Очистить ComboBox можно как от всех значений сразу, так и удалить один или несколько значений (по одному) из списка.

Очистка ComboBox от всего списка значений:

Очистка ComboBox от одного значения:

ComboBox1.RemoveItem Index

где Index — порядковый номер элемента в списке ComboBox, нумерация начинается с нуля.

Автоматическое заполнение ComboBox

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

Заполнение ComboBox на форме

Автоматическое заполнение элемента управления ComboBox на пользовательской форме осуществляется с помощью процедуры UserForm_Initialize, размещенной в модуле этой формы:

Private Sub UserForm_Initialize()

    ComboBox1.List = Лист8.[A1:A15].Value

End Sub

Или по одному:

Private Sub UserForm_Initialize()

    With ComboBox1

        .Clear

        .AddItem «Апельсин»

        .AddItem «Банан»

        .AddItem «Виноград»

        .AddItem «Груша»

        .AddItem «Хурма»

    End With

End Sub

Заполнение ComboBox на листе

Автоматическое заполнение элемента управления ComboBox из коллекции «Элементы ActiveX» на рабочем листе осуществляется с помощью процедуры Workbook_Open, размещенной в модуле «ЭтаКнига»:

Private Sub Workbook_Open()

    Лист8.ComboBox1.List = Лист8.[A1:A15].Value

End Sub

Или по одному:

Private Sub Workbook_Open()

    With Лист8.ComboBox1

        .Clear

        .AddItem «Апельсин»

        .AddItem «Банан»

        .AddItem «Виноград»

        .AddItem «Груша»

        .AddItem «Хурма»

    End With

End Sub


Более подробно о заполнении данными ComboBox можно прочитать в статье о заполнении ListBox, так как оба эти элемента управления используют одинаковые способы заполнения.

Иногда возникает необходимость заполнения элементов управления ListBox и ComboBox уникальными значениями из диапазона ячеек с повторяющимся содержимым. Смотрите, как отсортировать уникальные элементы из списка с помощью объектов Collection и Dictionary.

Вы можете скачать файл Excel с представленными выше примерами. Файл упакован в ZIP-архив. Для проверки работоспособности кода, непосредственно в редакторе VBA помещайте курсор внутри тела каждой процедуры и нажимайте кнопку «Run Sub».

ComboBox — значение по умолчанию

Добавление значения по умолчанию вручную

Значение по умолчанию для текстового поля ComboBox можно задать вручную в окне свойств (Properties) выбранного элемента управления:

Выберите ComboBox на форме в редакторе VBA и в окне Properties в поле Value впишите нужное значение.

Программное добавление значения по умолчанию

Добавление произвольного значения по умолчанию в текстовое поле ComboBox при инициализации пользовательской формы:

Private Sub UserForm_Initialize()

    With ComboBox1

        .AddItem «Камень»

        .AddItem «Ножницы»

        .AddItem «Бумага»

        ‘Добавление произвольного значения по умолчанию

        .Value = «Выберите значение»

    End With

End Sub

Добавление значения по умолчанию в текстовое поле ComboBox из имеющегося списка:

Private Sub UserForm_Initialize()

    With ComboBox1

        .AddItem «Камень»

        .AddItem «Ножницы»

        .AddItem «Бумага»

        ‘Добавление значения по умолчанию из списка

        .ListIndex = 0

    End With

End Sub

Нумерация списка ComboBox начинается с нуля, поэтому приведенный выше код отобразит значение по умолчанию — «Камень».


Хитрости »

5 Май 2011              115240 просмотров


Очень часто при работе с формами(UserForm) приходится заполнять значениями КомбоБоксы(ComboBox) и ТекстБоксы(TextBox). Иногда однотипными данными. Или очистить их все после выполнения какого-либо действия. А может проверить, все ли элементы заполнены, прежде чем продолжать действие. Если КомбоБоксов/ТекстБоксов пару штучек — не проблема

TextBox1 = ""
TextBox2 = ""

и всех делов. А если их порядка двадцати? Или больше? Мало того, что писать это все долго, так еще и код растягивается, как портянка. Но это можно сделать гораздо проще и удобнее. Воспользоваться можно несколькими способами. Этот способ наиболее популярен, если необходимо произвести однотипные действия со всеми ТекстБоксами на форме:

Sub All_TextBoxes()
    Dim oControl As Control
    For Each oControl In UserForm1.Controls
        If TypeOf oControl Is MSForms.TextBox Then
            oControl.Value = ""
        End If
    Next oControl
End Sub

В примере элементы формы очищаются, но в код можно подставить любое действие — добавление нового элемента списка(для ComboBox), поменять представление данных в TextBox, проверить наличие данных в проверяемом элементе и т.д. Тут уж зависит от поставленной задачи. Конечно, подобным способом можно проделать разные действия и с остальными элементами формы. Только надо будет заменить тип для проверки элементов:

ComboBox - MSForms.ComboBox
CheckBox - MSForms.CheckBox
CommandButton - MSForms.CommandButton
Frame - MSForms.Frame
Image - MSForms.Image
Label - MSForms.Label
ListBox - MSForms.ListBox
MultiPage - MSForms.MultiPage
SpinButton - MSForms.SpinButton
TabStrip - MSForms.TabStrip
ToggleButton - MSForms.ToggleButton

Это не единственный способ проделывания однотипных действий с элементами формы. Код ниже использует имена элементов для обращения к ним:

Sub All_TextBoxes()
    Dim li As Long
    For li = 1 To 10
        UserForm1.Controls("TextBox" & li).Value = li
    Next li
End Sub

Недостаток данного метода: имена элементов должны строго соответствовать используемым в коде и лишь нумерация на конце имени должна различаться. За нумерацию отвечает переменная li и, конечно, цикл, в котором задается начальное и конечные значения. В примере ТекстБоксам с именами от «TextBox1» до «TextBox10» будут подставлены значения номеров самих ТекстБоксов. Но такой недостаток может быть очень полезным. Например, если необходимо проделать действия не над всеми ТекстБоксами, а лишь над некоторыми из них. Тогда все, что необходимо дать ТекстБоксам определенные имена с нумерацией(«ToDB1″,»ToDB2» и т.д.) и в зависимости от имени можно проделывать различные действия: стирать значения, менять свойства элементов и т.д.
И есть еще один плюс такого подхода: когда необходимо заполнить значения ТекстБоксов значениями ячеек. Скажем надо заполнить 10 ТекстБоксов(с именами TextBox1, TextBox2, TextBox3 и т.д.) из ячеек диапазона A2:A11 листа с именем «Лист2″(т.е. из 10 ячеек, начиная с ячейки A2). Код будет выглядеть так:

Sub Fill_TextBoxes_FromCells()
    Dim li As Long
    For li = 1 To 10
        UserForm1.Controls("TextBox" & li).Value = Sheets("Лист2").Range("A" & li).Value
        'или применить Cells вместо Range
        'UserForm1.Controls("TextBox" & li).Value = Sheets("Лист2").Cells(li, 1).Value
    Next li
End Sub

Подробнее про обращение к диапазонам из VBA можно узнать из этой статьи: Как обратиться к диапазону из VBA

Скачать пример

  Tips_Macro_WorkWithGroupControls.xls (51,5 KiB, 4 052 скачиваний)

P.S. Небольшое дополнение: нужные элементы можно просто помещать внутрь объекта Frame. Тогда можно будет применять цикл исключительно по элементам внутри этого Frame(предположим, что Frame называется Frame1):

Sub All_TextBoxes_InFrame()
    Dim oControl As Control
    For Each oControl In Frame1.Controls
        If TypeOf oControl Is MSForms.TextBox Then
            oControl.Value = ""
        End If
    Next oControl
End Sub

Кстати говоря, примерно так же можно перебрать элементы ActiveX не на форме, а на листе(вставляются на лист через вкладку Разработчик(Developer)Вставить(Insert)Элементы ActiveX(ActiveX Controls)). Например, снимем флажки со всех CheckBox-ов:

Sub Off_ActiveXCheckBoxes()
    Dim oControl
    'цикл по всем объектам на листе
    For Each oControl In ActiveSheet.DrawingObjects
        'определяем тип объекта - должен быть OLEObject(так определяется ActiveX)
        If TypeName(oControl) = "OLEObject" Then
            'необходимо дополнительно проверить тип элемента
            If TypeOf oControl.Object Is MSForms.CheckBox Then
                oControl.Object.Value = 0
            End If
        End If
    Next oControl
End Sub

Для этих элементов на листе в строке TypeOf oControl.Object Is MSForms.CheckBox для проверки типа(MSForms.CheckBox) используются те же значения, что и для контролов на форме. Перечень приведен выше.
Но помимо ActiveX(к слову устаревших и не рекомендованных к использованию) на листе могут быть и другие, более новые флажки — элементы форм(вставляются на лист через вкладку Разработчик(Developer)Вставить(Insert)Элементы управления формы(Form Controls)). К ним подход уже другой:

Sub Off_ShapeCheckBoxes()
    Dim oControl
    'цикл по всем объектам на листе
    For Each oControl In ActiveSheet.DrawingObjects
        'определяем тип объекта - если это Элемент форм, то будет указание на конкретный тип
        If TypeName(oControl) = "CheckBox" Then
            oControl.Value = 0
        End If
    Next oControl
End Sub

В данном случае для определения конкретного типа контрола используется TypeName. В коде выше нам нужны CheckBox-ы и на них и проверяем. А вот список основных элементов форм, которые доступны по умолчанию для всех версий для вставки на лист:
Button — кнопка
DropDown — поле со списком
CheckBox — флажок
Spinner — счетчик
ListBox — список
OptionButton — радиокнопка
GroupBox — группа(рамка)
Label — надпись
ScrollBar — полоса прокрутки

Если совместить, то можно снять флажки со всех checkBox-ов — и ActiveX и Элементов форм:

Sub Off_AllCheckBoxes()
    Dim oControl
    'цикл по всем объектам на листе
    For Each oControl In ActiveSheet.DrawingObjects
        'определяем тип флажка: ActiveX или Элемент форм
        Select Case TypeName(oControl)
        Case "OLEObject"    'ActiveX - необходимо дополнительно проверить тип элемента
            If TypeOf oControl.Object Is MSForms.CheckBox Then
                oControl.Object.Value = 0
            End If
        Case "CheckBox"     'Элемент форм CheckBox
            oControl.Value = 0
        End Select
    Next oControl
End Sub

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


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

Skip to content

VBA ComboBox Excel Macros Examples Codes Adding Clearing Items

Home » Excel VBA » VBA ComboBox Excel Macros Examples Codes Adding Clearing Items

VBA ComboBox Excel Macros Examples Codes for Adding new Items,Adding new Items to another ComboBox based on selection of first ComboBox ,Clearing Tutorials. ComboBox in Excel VBA is one of most useful control in the Excel. You can show the list of items in the ComboBox and user can select any one item and do different operations. In this tutorial, we will explain different example on using ComboBox.

ComboBox in Excel VBA – Example Cases:

  • Add Items to ComboBox while opening Workbook
  • Add Items to ComboBox2 based on ComboBox1 selection
  • Get data to TextBox based on ComboBox2 selection
  • Clear ComboBox Items
  • DownLoad:Example File

Sample ComboBox Design:

  1. GoTo Developer Tab from Menu
  2. GoTo Insert from Controls Part
  3. Insert two ComboBox’s and two TextBox’es from ActiveX Controls
  4. The final design should be as shown below
Screen Shot:

ComboBox in Excel VBA-Design1

Add Items to ComboBox while opening Workbook

You can Add items to the ComboBox while opening the Excel Workbook. The following example will show you how to populate the items in ComboBox while opening excel file.

Code:
Private Sub Workbook_Open()
    
    Application.EnableEvents = False
    'Clear ComboBox1 Items
    Call Clear_ComboBox
    
     'Add Items to ComboBox1 in Sheet1 while opening workbook
    With Sheet1.ComboBox1
        .AddItem "Fruits"
        .AddItem "Vegetables"
        .AddItem "Soaps"
        .AddItem "Beverages"
    End With
     Application.EnableEvents = True
End Sub

Output:

Here is the screen-shot of the ComboBox1 with items.
ComboBox in Excel VBA-Add Items

Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. From Project Explorer Double Click on ThisWorkbook
  4. Copy the above code and Paste in the code window
  5. Save the file as macro enabled workbook and Close it
  6. Open the file to see the output
  7. You should see the Items in ComboBox1 as shown above
Add Items to ComboBox2 based on ComboBox1 selection

You can add items to ComboBox2 based on ComboBox1 selection. It is helpful while developing tools. You can provide the user to select item from first ComboBox and add items to second comboBox based on first ComboBox Selection.Please find the following example below.

Code:
'Get Items to ComboBox2 based on ComboBox1 selection
Private Sub ComboBox1_Change()

    'Variable Declaration
    Dim iCnt As Integer
    
    'Clear Combobox2 before loading items
    ComboBox2.Clear
 
    With ComboBox2
        Select Case ComboBox1
            Case "Fruits"
                .AddItem "Apple"
                .AddItem "Pomegranate"
                .AddItem "Grape"
                .AddItem "Pineapple"
                .AddItem "Gouva"
            Case "Vegetables"
                .AddItem "Tomato"
                .AddItem "Brinjal"
                .AddItem "Radish"
                .AddItem "Potato"
                .AddItem "Onion"
            Case "Beverages"
                .AddItem "Pepsi"
                .AddItem "Limca"
                .AddItem "Miranda"
                .AddItem "Sprite"
                .AddItem "Coco Cola"
            Case "Soaps"
                .AddItem "Lux"
                .AddItem "Rexona"
                .AddItem "Dove"
                .AddItem "Lifeboy"
                .AddItem "Liril"
        End Select
    End With

End Sub

Output:

Here is the screen-shot to show you adding the items to second ComboBox based on first ComboBox Selection.
ComboBox in Excel VBA-Add Items to ComboBox2

Instructions:
  1. Please follow the above mentioned design steps
  2. Goto Developer Tab from the menu, Click on Design Mode in the Sheet1
  3. Double Click on ComboBox1
  4. Copy the above code and Paste in the code window
  5. Goto Developer Tab from the menu, Click on Design Mode in the Sheet1
  6. Now select Item from Combox1. Now you can see the items in Combox2 based on ComboBox1 selection
Get data to TextBox based on ComboBox2 selection

The following example will show you how to get data to TextBox based on ComoBox2 selection.

Code:
'Get Price based on ComboBox2 selection
Private Sub ComboBox2_Change()
    
    'Variable Declaration
    Dim iRow As Integer
    iRow = 1
    
    'Clear Combobox2 before loading items
    TextBox1.Text = ""
    
    'Get Price based on ComboBox2 selection
    Do
        iRow = iRow + 1
        
    Loop Until ComboBox2.Text = Sheets("Data").Cells(iRow, 3)
    TextBox1.Text = Sheets("Data").Cells(iRow, 4)
    TextBox2.Text = Sheets("Data").Cells(iRow, 5)

End Sub
Output:

Here is the sample screen-shot.
ComboBox in Excel VBA-Output

Instructions:
  1. Please follow the above mentioned design steps
  2. Goto Developer Tab from the menu, Click on Design Mode in the Sheet1
  3. Double Click on ComboBox2
  4. Copy the above code and Paste in the code window
  5. Goto Developer Tab from the menu, Click on Design Mode in the Sheet1
  6. Now select Item from Combox1 & Combox2. Now you can see the Price and availability of item to the Textbox as aoutput based on ComboBox2 selection
Clear ComboBox Items

You can clear the ComboBox using Clear method. The following procedure will show how to clear the ComboBox items, this procedure will clear the ComboBox items before loading an items to ComboBox.

Code:
Sub Clear_ComboBox()
    
    'Clear ComboBox &amp;amp;amp; TextBox data
    With Sheet1
        .ComboBox1.Clear
        .ComboBox2.Clear
        .TextBox1.Text = ""
        .TextBox2.Text = ""
    End With

End Sub
Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Insert a new module from Insert menu
  4. Copy the above code and Paste in the code window
  5. We can call this procedure to clear ComboBox items before loading items to ComboBox
  6. It will clear items from ComboBox
Example File

Download the example file and Explore it.
ANALYSISTABS – Combo Box

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

  • ComboBox in Excel VBA – Example Cases:
    • Sample ComboBox Design:

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

36 Comments

  1. Jared
    February 20, 2014 at 6:24 AM — Reply

    I’d like to do the same thing as above with the first two comboboxes, but instead of using item hard-coded into the programming, use group of cells, so, where you see

    Select Case ComboBox1
    Case “Fruits”
    .AddItem “Apple”
    .AddItem “Pomegranate”
    .AddItem “Grape”
    .AddItem “Pineapple”
    .AddItem “Gouva”

    i’d like it to refer to cells that have those values in them, and tell it to keep looking untill it finds a blank cell (meaning theres no more values) so i can feel free to add and delete values as i want, right in the sheet. i’m sure this is possible, and i’ve seen it done, but can someone show me using the above example?

    thanks!

  2. PNRao
    February 20, 2014 at 11:18 PM — Reply

    Hi Jared,

    Here is the solution.
    Assuming that you have the following data in Column A and B:

    Fruits Apple
    Fruits Pomegranate
    Fruits Grape
    Fruits Pineapple
    Fruits Gouva
    Vegetables Tomato
    Vegetables Brinjal
    Vegetables Radish
    Vegetables Potato
    Vegetables Onion
    Beverages Pepsi
    Beverages Limca
    Beverages Miranda
    Beverages Sprite
    Beverages Coco Cola
    Soaps Lux
    Soaps Rexona
    Soaps Dove
    Soaps Lifeboy
    Soaps Liril
    Here is the code:


    Private Sub ComboBox1_Change()
    Dim iCntr As Integer

    iCntr = 1
    'Looping until column A is blank
    ComboBox2.Clear
    Do While Sheets("Sheet1").Cells(iCntr, 1) <> "
    'Checking if the column a is equals to ComboBox1 selected value
    If Sheets("Sheet1").Cells(iCntr, 1) = ComboBox1.Value Then
    'Adding items to ComboBox2, respective items in the Column B
    ComboBox2.AddItem Sheets("Sheet1").Cells(iCntr, 2)
    End If
    iCntr = iCntr + 1
    Loop

    End Sub

    Hope this helps.

    Thanks-PNRao!

  3. Amith
    April 25, 2014 at 1:12 PM — Reply

    Hi,
    I want to add quantity column and want a Total Quantity field in Combo Box with capability to auto sum quantity of Apple.(Suppose we have entered Apple in Row 2 as 100 Qty and Row 5 as 50 Qty in Data sheet.) And when anybody selects Fruit>Apple it will display Quantity as 150. This new part i want to add keeping rest of thing same. Need your help….

  4. PNRao
    April 26, 2014 at 10:52 AM — Reply

    Hi Amith,
    You can loop through the rows and check for the ‘apple’ and the add the respective qty. For example:
    in FruitComboBox_change()
    [vb]
    ‘Assuming Fruit Name in Column A and Qty in Column B
    If Trim(FruitComboBox.Value) <> «» Then
    lRow = 200 ‘Your last row in data sheet
    totQty = 0

    For iCntr = 1 To lRow
    If Sheets(«Data»).Cells(iCntr, 1) = FruitComboBox.Value Then totQty = totQty + Sheets(«Data»).Cells(iCntr, 2)
    Next
    ‘Display the final Qty
    QtyTextBox = totQty
    End If
    [/vb]

    Hope this helps!
    Thanks-PNRao!

  5. Bhawesh
    December 17, 2014 at 5:33 PM — Reply

    Dear sir,
    I would like to know that how i linked different cells rows with the same combobox which populated in different textboxes. kindly help.. Regards, Bhawesh

  6. sharmila
    January 5, 2015 at 10:05 PM — Reply

    good tutorial and well defined example

  7. PNRao
    January 6, 2015 at 8:09 PM — Reply

    Thank you Sharmila! We are glad we could help and hearing good feedback from our readers.
    -PNRao!

  8. Farbood
    February 13, 2015 at 11:10 PM — Reply
  9. Jayanth
    February 16, 2015 at 12:41 PM — Reply

    Hi!
    this is a good and easy to understand example.

    the query i have in my mind is that..

    i have a vb program and an excel sheet separately and i have linked it thru OLEDB connection.

    i have two combo boxes and i have to read data from excel sheet .

    how do i do that ?

  10. klorvalex
    February 25, 2015 at 10:07 PM — Reply

    Good. This helps me a lot. Thanks.

  11. PNRao
    March 2, 2015 at 7:17 PM — Reply

    Thank you klorvalex! You are most welcome to our blog. – PNRao!

  12. PNRao
    March 2, 2015 at 7:26 PM — Reply

    You can get the data from Excel to an arry and assign to ComboBox:
    Example:

    ComboBox1.List=ArrData

    Thanks-PNRao!

  13. PNRao
    March 2, 2015 at 7:29 PM — Reply

    You are most welcome Farbood! We are very glad and happy to hear such a nice feedback.
    Thanks-PNRao!

  14. xuan truong NGUYEN
    August 1, 2015 at 6:11 AM — Reply

    Your explanations and templates are excellent .Thanks a lot

  15. PNRao
    August 2, 2015 at 3:39 AM — Reply

    Thanks for the feedback!
    Regards-PNRao!

  16. japheth
    February 24, 2016 at 7:37 PM — Reply

    Hi guys, am stuck somewhere, av been able to create 2 combo boxes in my form and populated the first one. my question is how can i link the two combo boxes so that the list is combo box 2 depends with the user’s selection in combo box one, which fetches data from an excel worksheet.
    Any help?..Thanx in ADVANCE …

    THIS IS MY CODE (for populating combo box 1)

  17. PNRao
    February 25, 2016 at 10:35 PM — Reply

    Assuming your you have two combo boxes on user form named ComboBox1 and ComboBox2:

    'Initiating ComboBox1 
    Private Sub UserForm_Initialize()
    ComboBox1.AddItem "Set 1"
    ComboBox1.AddItem "Set 2"
    ComboBox1.AddItem "Set 3"
    End Sub
    
    'Populating ComboBox2 while changing the value of ComboBox1
    Private Sub ComboBox1_Change()
    ComboBox2.Clear
    If ComboBox1.Value = "Set 1" Then
        ComboBox2.List = Sheets("YourSheetName").Range("A1:A5").Value
    ElseIf ComboBox1.Value = "Set 2" Then
        ComboBox2.List = Sheets("YourSheetName").Range("B1:B5").Value
    ElseIf ComboBox1.Value = "Set 3" Then
        ComboBox2.List = Sheets("YourSheetName").Range("C1:C5").Value
    End If
    End Sub
    
    

    Hope this helps, Thanks-PNRao!

  18. Roy
    March 1, 2016 at 4:06 PM — Reply

    Hi PNRao,

    Hope you are doing good.
    a very small query. i have a code in which i am taking the input through input box and those values are getting stored in defined cells.what i want to do is the values that i am taking as an input if any of the values is less then a particular value say suppose 50 then that particular cell will return the value with a color red.
    i was doing the following but its not executing anything.

    Dim i As Integer
    i = 1
    Do While Cells(i, 2).Value ”
    If Cells(i, 2).Value < 50 Then
    Cells(i, 2).Font.Color = vbRed
    i = i + 1
    End If
    Loop

    help would be much appreciated.

  19. Marcel Defensor
    March 4, 2016 at 9:30 AM — Reply

    I just can’t create a combobox code that extracts its items direct from a worksheet dependind on the value related to a particular cell. Something like ‘if “a1=2” then “items are this column” else “items are that column”‘.
    Any help will be useful. Thanks.

  20. PNRao
    March 5, 2016 at 6:03 PM — Reply

    Hi Roy,
    increment statement should be out side the if block:

    Sub sbChangeFontColorBasedOnCellValue()
    Dim i As Integer
    i = 1
    Do While Cells(i, 2) <> "
        If Cells(i, 2) < 50 Then
            Cells(i, 2).Font.Color = vbRed
        End If
        i = i + 1
    Loop
    End Sub
    

    Thanks-PNRao!

  21. PNRao
    March 5, 2016 at 6:08 PM — Reply
  22. Jahanzeb
    May 5, 2016 at 4:13 PM — Reply

    Thanks a Lot, It will pay you for your kind support

  23. Bhupender
    May 16, 2016 at 1:46 AM — Reply

    Hi,

    Sir I am a new learner of vba. so could you please uploade the data file of above example. so that i can understand.

    Regards
    Bhupender Singh
    Big fan of yours tutorial

  24. Edgardo
    August 23, 2016 at 11:25 AM — Reply

    i want to select item’s quantity from combo-box and calculate price and it will input in textbox using Visual Basic Studio

  25. Edgardo
    August 23, 2016 at 11:26 AM — Reply

    Hi guys can you please help me? I want select item’s quantity from combo-box and calculate price.

  26. ravikumar
    August 31, 2016 at 3:48 PM — Reply

    hi,

    iam a new to vba code..i have an excel sheet in that I create dropdown list..like

    IF process is main then the list items are
    timeline
    kaizen
    datatabel
    fifolane

    when ever I will select the drop down list value according to that in next cell data will come autopopulate… can you send the code in vba

  27. ravikumar
    August 31, 2016 at 6:17 PM — Reply

    ‘Get Price based on ComboBox2 selection
    Do
    iRow = iRow + 1

    Loop Until ComboBox2.Text = Sheets(“Data”).Cells(iRow, 3)
    TextBox1.Text = Sheets(“Data”).Cells(iRow, 4)
    TextBox2.Text = Sheets(“Data”).Cells(iRow, 5)

    End Sub
    can you explain this code….
    here data in the sense wat…can you pls explain this…this will helpful for me…

  28. pradeep
    September 20, 2016 at 10:53 AM — Reply

    im unable to download the file

  29. PNRao
    October 23, 2016 at 9:46 AM — Reply

    Updated the link, please download the file.
    Thanks-PNRao!

  30. vasim
    January 10, 2017 at 2:22 PM — Reply

    please upload example excel file.

  31. Himanshu
    January 11, 2017 at 4:33 PM — Reply

    Dear Sir,

    Excellent tutorial. I need help with intermediate and advanced excel tutorials. Will you be able to provide tutorials in a structured course format. Thanks

  32. Rajesh
    May 29, 2017 at 1:55 AM — Reply

    Hi. I am stuck at a place where I am selecting the value from the first Combo box and according the value is listed in the second Combo box. Now the challenge for me here is the values of the second combo box is too long , during display the value is left aligned which is easier for the user to select the item but the once the value is selected the value is displayed right aligned which is difficult to identify what was selected. How can I show the value initially and on selecting also the value is left aligned.

    Kindly help.

  33. Catherine Thomas
    June 21, 2017 at 9:21 AM — Reply

    I downloaded this code and modified it for my 2 boxes and it works perfectly – thank you!!!

    Now, I have a project where I need to add a 3rd dependent box. Sticking with the .additem way, how Shoukd I wrote the code to get box 2 items to box?

    Thank you so much! I’m struggle with the combinations.

  34. Bhupesh
    August 21, 2017 at 6:28 PM — Reply

    Hello Sir,

    I want to know how to make a combo box on a userform with search suggestions.

    The combox shall have items in it already from which i can choose one. However if the no. of items are too many , then in that case i may write the item name and its suggestion shall be reflected.
    like if i type ” Ram” in the combobox then i shall get the suggestion like ” Ramesh” & ” Ramalingam” etc.

    Kindly help me in this .

  35. Chirag Prajapati
    January 24, 2018 at 3:46 PM — Reply

    Hi…
    Thanks for your tutorial.
    I get one problem.
    After coding as above i get result but after closing excel sheet program need to run manually.
    It doesn’t work with auto run.

  36. LLY
    February 15, 2019 at 5:44 PM — Reply

    Hiya,

    Would it be possible to use Loop to identify a group of combo box? For example :

    For i = 1 to 10
    Sheets(“Sheet1”).combobox(i).List = Array(“Apple”, “Banana”, “Coconut”)
    next i

    Thank you

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Понравилась статья? Поделить с друзьями:
  • Vba excel очистить колонку
  • Vba excel очистить значения ячеек
  • Vba excel очистить диапазон ячеек на листе
  • Vba excel очистить все фильтры
  • Vba excel очистить весь лист