Excel vba listbox снять выделение

 

.
при клике на  ListBox2 выделение с  ListBox1 снимается
при клике на  ListBox1 выделение с  ListBox2 НЕ снимается

ListBox1 (1,2,3) — мультиселект
ListBox2 (4,5,6) — одиночная

Прикрепленные файлы

  • Книга1.xlsm (17.31 КБ)

Изменено: невеДимка Соколов14.10.2019 11:01:14

 

Апострофф

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

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

невеДимка Соколов, вместо ListBox1_Click попробуйте ListBox1_Change

 

ListBox1_Change работает только один раз.

 

Апострофф

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

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

#4

14.10.2019 12:29:15

Цитата
невеДимка Соколов написал:
Работает только один раз.

Не допонял — что именно не работает и в чём задача?

 

невеДимка Соколов

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

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

#5

14.10.2019 13:34:00

нажимаю на 4 (ЛБ2). Нажимаю на 1(ЛБ1). выделение 4 сбрасывается
нажиаю снова на 4. потом нажимаю на 1 выделение не сбрасывется. значение то не поменялось.

Цитата
Апострофф написал: в чём задача

Надо чтоб сбрасывалось выделение при переходе на другой листбокс

 

Апострофф

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

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

#6

14.10.2019 13:52:14

Цитата
невеДимка Соколов написал:
Надо чтоб сбрасывалось выделение при переходе на другой листбокс

не тогда _Enter напрашивается —

Код
Private Sub ListBox1_Enter()
ListBox2.ListIndex = -1
End Sub

Private Sub ListBox2_Enter()
Dim i&
For i = 0 To ListBox1.ListCount - 1
    ListBox1.Selected(i) = False
Next
End Sub
 

невеДимка Соколов

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

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

#7

15.10.2019 07:53:11

Цитата
Апострофф написал:
не тогда _Enter напрашивается —

Почему то в родном файле так не работает, но.. если оба листбокса сделать мульти, то не снимает выделение ( снова работает один раз)

Прикрепленные файлы

  • Книга1.xlsm (18.39 КБ)

 

Апострофф

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

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

#8

15.10.2019 08:59:41

невеДимка Соколов, трудно вас понять: перечитайте своё последнее сообщение внимательно.

Цитата
невеДимка Соколов написал:
если оба листбокса сделать мульти, то не снимает выделение

если оба мульти, то и обработчики _Enter должны быть одинаковы?

Код
Private Sub ListBox1_Enter()
Dim i&
For i = 0 To ListBox2.ListCount - 1
    ListBox2.Selected(i) = False
Next
End Sub

Private Sub ListBox2_Enter()
Dim i&
For i = 0 To ListBox1.ListCount - 1
    ListBox1.Selected(i) = False
Next
End Sub
 

невеДимка Соколов

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

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

#9

15.10.2019 09:33:27

Цитата
Апострофф написал:
должны быть одинаковы

Извините.

Содержание

  1. Reset listbox selection in VBA
  2. 6 Answers 6
  3. Linked
  4. Related
  5. Hot Network Questions
  6. Subscribe to RSS
  7. Объект ListBox (Outlook Forms Script)
  8. Замечания
  9. Стили элемента ListBox
  10. События
  11. Методы
  12. Свойства
  13. Поддержка и обратная связь
  14. The Complete Guide to Excel VBA Form Control ListBoxes
  15. The VBA Tutorials Blog
  16. Table of Contents
  17. Introduction
  18. Change ListBox Selection Type

Reset listbox selection in VBA

I’m trying to ‘reset’ a listbox in Excel VBA when a form closes. Currently when I use the userform1.hide function the form disappears but when I open it up again using the .show function it still has the previous selections in it. As someone who is relatively new to this can anyone help?

The code for the listboxes is as follows:

Thanks in advance everyone,

6 Answers 6

If you want to clear ONLY the selection (as you are using hide, not unload) then use:

If it is a multiselect listbox, you need to use:

this will clear the selection by setting it to single selection only and then clearing the selection, then setting the functionality to multi select again.

If you want to clear the entire list box (the options that you select) use:

try this code to Clear listbox in VBA

To reset the apparent item selected in the listbox, try:

There will be no apparent item in the listbox control after that.

Hide and show has no effect. If you want to use «brute force», use unload then load, but it will reset everything (not just the radio buttons) and will be memory consuming (well, if your form doesn’t contain thousands of components and your computer is recent etc etc it will be fine though)

another way to do what you want is simply to run through all radio buttons and uncheck them all

Adapting LBPLC’s clever technique, here’s a single solution that works in all cases:

But note that this doesn’t work if called from within the ListBox control’s VBA Change event. Probably, that’s due to Excel’s ListBox change-event code freezing the effective state of the MultiSelect property during processing, in order to prevent unstable conditions for its own processing.

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Объект ListBox (Outlook Forms Script)

Отображает список значений и позволяет выбирать одно или несколько значений.

Замечания

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

ListBox может отображаться в виде списка или группы элементов управления OptionButton или CheckBox.

Свойством по умолчанию для ListBox является свойство Value .

Событием по умолчанию для ListBox является событие Click .

В раскрывающийся элемент ListBox невозможно поместить текст.

Стили элемента ListBox

Вы можете выбрать любой из двух стилей представления элемента ListBox. Это выражается свойством ListStyle . Каждый из них реализует собственный способ выбора элементов в списке.

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

Если стиль равен 1, в начале каждой строки отображается optionButton или CheckBox . В этом случае для выбора элемента пользователь нажимает кнопку или устанавливает флажок. Флажки отображаются только в том случае, если свойство MultiSelect имеет значение True.

События

Имя Описание
Click Происходит, когда пользователь окончательно выбирает для элемента управления значение, которое содержит несколько возможных значений.

Методы

Имя Описание
AddItem Для элемента ListBox с одним столбцом метод AddItem добавляет элемент в список. Для многоколоний ListBox этот метод добавляет строку в список.
Clear Удаляет все записи в списке в ListBox.
RemoveItem Удаляет строку из списка в ListBox.

Свойства

Имя Описание
BackColor Возвращает или задает значение Long , указывающее цвет фона объекта . Для чтения и записи.
BorderColor Возвращает или задает значение Long , указывающее цвет границы объекта. Для чтения и записи.
BorderStyle Возвращает или задает целое число , указывающее тип границы элемента управления. Для чтения и записи.
BoundColumn Возвращает или задает значение Variant , определяющее источник данных в многоколоний ListBox. Для чтения и записи.
Столбец Возвращает или задает значение Variant , представляющее одно значение, столбец значений или двумерный массив для загрузки в ListBox. Для чтения и записи.
ColumnCount Возвращает или задает значение Long , представляющее количество столбцов, отображаемых в списке. Для чтения и записи.
ColumnHeads Возвращает или задает логическое значение, указывающее, отображается ли одна строка заголовков столбцов. Для чтения и записи.
ColumnWidths Возвращает или задает значение String , указывающее ширину каждого столбца в многоколоний ListBox. Для чтения и записи.
Enabled Возвращает или задает логическое значение, указывающее, может ли элемент управления получать фокус и реагировать на события, созданные пользователем. Для чтения и записи.
ForeColor Возвращает или задает значение Long , указывающее цвет переднего плана объекта. Для чтения и записи.
IMEMode Возвращает или задает целое число , указывающее режим времени выполнения по умолчанию редактора метода ввода (IME) для элемента управления. Для чтения и записи.
IntegralHeight Возвращает или задает логическое значение, указывающее, отображает ли ListBox полные строки текста в списке или частичные строки. Для чтения и записи.
List Возвращает или задает значение Variant , представляющее указанную запись в ListBox. Для чтения и записи.
ListCount Возвращает значение Long , представляющее количество записей списка в элементе управления . Только для чтения.
ListIndex Возвращает или задает значение Variant , представляющее текущий выбранный элемент в элементе ListBox. Для чтения и записи.
ListStyle Возвращает или задает целое число , указывающее визуальный вид списка в ListBox. Для чтения и записи.
Locked Возвращает или задает логическое значение, указывающее, можно ли изменять элемент управления. Для чтения и записи.
MatchEntry Возвращает или задает целое число , указывающее, как ListBox выполняет поиск в списке по типу пользователя. Для чтения и записи.
MouseIcon Возвращает значение String , представляющее полное имя пути настраиваемого значка, назначаемого элементу управления. Только для чтения.
MousePointer Возвращает или задает целое число , указывающее тип указателя, отображаемого при наведении указателя мыши на определенный объект. Для чтения и записи.
MultiSelect Возвращает или задает целое число , указывающее, допускает ли объект несколько выделений. Для чтения и записи.
Selected Возвращает или задает логическое значение, указывающее состояние выделения элементов в ListBox. Для чтения и записи.
SpecialEffect Возвращает или задает целое число , указывающее внешний вид объекта. Для чтения и записи.
Текст Возвращает или задает строку, указывающую текст в элементе ListBox, изменяя выбранную строку в элементе управления . Для чтения и записи.
TextAlign Возвращает или задает целое число , указывающее способ выравнивания текста в элементе управления . Для чтения и записи.
TextColumn Возвращает или задает значение Variant , которое идентифицирует столбец в элементе ListBox для отображения пользователю. Для чтения и записи.
TopIndex Возвращает или задает значение Long , представляющее индекс элемента списка, отображаемого в верхней позиции списка. Для чтения и записи.
Value (Значение) Возвращает или задает значение Variant , указывающее значение в BoundColumn выбранных строк. Для чтения и записи.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

The Complete Guide to Excel VBA Form Control ListBoxes

The VBA Tutorials Blog

Table of Contents

Introduction

This VBA Guide will teach you everything you could possibly want to know about handling Excel Form Control Listboxes using VBA. When I say “Form Control” ListBox, I’m talking about this little guy located under “Form Controls” on the Developer Tab > Insert menu:


Form Control ListBox

If you want to read more complete guides to Form Control or ActiveX Controls, visit my ActiveX and Form Control Guides page.

Before I get criticized, yes, I know the formal term is the two-word phrase List Box but I’m partial to referring to it like you would when writing a VBA macro: ListBox. You’ll find I use them interchangeably throughout this guide.

I made a calendar form using Excel Form Control ListBoxes, which I’ll reference throughout this guide as we learn how to manipulate our listboxes with VBA macros.


Excel ListBox Form

In the form control world, a listbox contains all the items in your list with an up and down scroll bar on the right side. If it’s a dropdown list your after, you need to try a combobox.

In this tutorial, I’ll show you how to select items, enable multiple selections, return the value of your listbox, link your listbox to a range, assign a macro to your listbox and loop through all the listboxes in your form — all using VBA!

Change ListBox Selection Type

How you control the selected values in a listbox using VBA depends largely on what you’ve chosen for your Selection Type. That’s why we’re starting here, first. The selection type can be changed by right clicking your ListBox, selecting Format Control and clicking the Control tab. Your choices are:

  1. Single — allows only one selection (xlNone).
  2. Multi — allows multiple selections (xlSimple).
  3. Extend — allows multiple selections and allows you to select a range of items in the list by shift-clicking (xlExtended).


Selection Type

Let’s change the selection type of our listboxes using VBA. Remember, the listbox name can be found in the upper left of Excel when you have your listbox selected:


List Box 1

Each of the three methods below can be used to change the MultiSelect property to any of the three acceptable values (xlNone, xlSimple and xlExtended).

Источник

excel vba listbox

The Excel VBA ListBox is a list control that allows you to select (or deselect) one or more items at time. This is compared to the VBA ComboBox which only allows you to select a single items from a drop down list. Let us explore how to create, clear and make a VBA ListBox let you select multiple items.

Create a Excel Form ListBox (Form Control)

To create an Excel Form ListBox you need to first make sure you can see the Developer Tab. Next go to Controls and select the ListBox. Place the ListBox on the Worksheet. You can right click on it to set the properties.
excel vba listbox

Using the Form ListBox

To add items to set items in a From ListBox is easiest by providing an Excel Range on your Worksheet that contain values for options.

Select Excel Range as ListBox Items

To add an Excel Range as Items for a ListBox right-click on the object and go to Format Control. Next go to the Control tab.
Configure a VBA ListBox
As you can see we managed to:

  • Set the Input range for the items in the Form ListBox
  • Set the Cell Link range for the selected item

The Excel Form ListBox is an option to use if you need a simple way to limit input options for your users in an spreadsheet.

Using Form ListBox does not make much sense as just as well we have Data Validation allowing you to set a drop down list to any Excel cell. See my post on Excel Cascading Drop-downs if you want to see how powerful this can be.

Beware in below examples I am using the ActiveX ListBox instead!

Create a VBA ListBox (ActiveX)

Now let us explore the adding Items to a Listbox using VBA. For this purpose it is easier and more convenient to use an ActiveX ListBox control (which I call the VBA ListBox) instead of the previously used Form ListBox:
vba listbox
In examples below I will be adding code to the Worksheet module in which I added a ActiveX ListBox control named ListBox1.
vba listbox name

Add Items to ListBox

To add VBA Add Items to the VBA ListBox use the AddItem function.

'Syntax
AddItem ( itemValue, itemOrder )
'itemValue - the value you want to add to your list
'itemOrder - the position in the VBA ListBox at which you want to insert your item (first is 0)

Examples of adding items to a ActiveX ListBox with VBA:

'Add Item Car
ListBox1.AddItem "Car"
'Add Item Bus
ListBox1.AddItem "Bus"
'Add Item Plane as second
ListBox1.AddItem "Plane", 1
'Add Item Plane
ListBox1.AddItem "Tesla"

The resulting VBA ListBox. Notice that Plane is second in the list:
add items to vba listbox
This list will work identically to the Excel Form ListBox.

Clear items in ListBox

To Clear/Empty items in a VBA ListBox simply use the Clear function:

'Add Item Car
ListBox1.AddItem "Car"

'Remove all items in the ListBox
ListBox1.Clear

Remove item from ListBox

To remove an item at a specific index or position in a VBA ListBox you need to use the RemoveItem function. Remember that the index of the first element is 0:

ListBox1.AddItem "Car"
ListBox1.AddItem "Plane"
ListBox1.AddItem "Bus"

'Remove the item "Plane"
ListBox1.RemoveItem(1)

Count items in ListBox

Counting items in a ListBox can be done using the Count function:

ListBox1.AddItem "Car"
ListBox1.AddItem "Plane"
ListBox1.AddItem "Bus"

'Count items
Debug.Print ListBox1.ListCount 'Result: 3

To enable multiselection on your VBA ListBox (ActiveX) use the MultiSelect property. The property can have one of the following values:

  • fmMultiSelectSingle – default property. You can only select 1 item
  • fmMultiSelectMulti – you can select multiple items. Clicking on an item will select (include it in the existing selected items) or deselect it (remove it from the existing selected items)
  • fmMultiSelectExtended – you can select multiple items. However, when you click on any item it will only select the current item. To select multiple items you need to click and hold and move the mouse up/down to select more items

By setting the MultiSelect option:

ListBox1.MultiSelect = fmMultiSelectExtended 

I am able now to select more items on my ListBox.
vba listbox multiselect

Select / Deselect items in ListBox

First we will try to understand how to check if an item on our ListBox is selected or not. For this we will use the Selected property.

ListBox1.AddItem "Car"
ListBox1.AddItem "Plane"
ListBox1.AddItem "Bus"

'...Click on Plane...

'Check which is selected
Debug.Print ListBox1.Selection(0) 'Result: False - Car is not selected
Debug.Print ListBox1.Selection(1) 'Result: True - Car is not selected
Debug.Print ListBox1.Selection(2) 'Result: False - Bus is not selected

To Select or Delect an item simply set the property to True (Selected) or False (Deselected):

ListBox1.AddItem "Car"
ListBox1.AddItem "Plane"
ListBox1.AddItem "Bus"

'Select Car
ListBox1.Selection(0) = True

'Check which is selected
Debug.Print ListBox1.Selection(0) 'Result: True - Car is not selected
Debug.Print ListBox1.Selection(1) 'Result: False - Car is not selected
Debug.Print ListBox1.Selection(2) 'Result: False - Bus is not selected

Skip to content

ListBox in Excel VBA – Adding, Clearing, Multiple Selection Examples

Home » Excel VBA » ListBox in Excel VBA – Adding, Clearing, Multiple Selection Examples

  • Listbox VBA

ListBox VBA Excel Example Macros Codes for Adding new Items,Moving all Items, selected Items from ListBox to another ListBox,clearing,Multi selection. VBA ListBox in Excel is one of finest control in the Excel. You can show the list of items in the listbox and user can select any item and do different operations. In this tutorial, we will explain different example on using ListBox in VBA Excel .

ListBox VBA Excel – Example Cases:

  • Load Items to ListBox while opening Workbook
  • Move all Items from ListBox1 to ListBox2
  • Move all Items from ListBox2 to ListBox1
  • Move selected Items from ListBox1 to ListBox2
  • Move selected Items from ListBox2 to ListBox1
  • Clear ListBox Items
  • Select Multiple Items from ListBox
  • DownLoad:Example File

ListBox VBA Excel -Sample ListBox Design:

  1. GoTo Developer Tab from Menu
  2. GoTo Insert from Controls Part
  3. Insert two ListBox’s and four Buttons from ActiveX Controls
  4. Select 1st Button and then Right Click Goto Properties and click on it
  5. Rename 1st button Name as “cmdMoveAllRight” and enter Caption as “>>”
  6. Select 2nd Button and Rename it as “cmdMoveSelRight” and enter Caption as “>”
  7. Select 3rd Button and Rename it as “cmdMoveSelLeft” and enter Caption as “<«
  8. Select 4th Button and Rename it as “cmdMoveAllLeft” and enter Caption as “<<«
  9. The final design should be as shown below
Screen Shot:

listbox in excel vba- Design

Load Items to ListBox while opening Workbook

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

Code:
Private Sub Workbook_Open()
       
    'Add Items to ListBox1 in Sheet1 while opening workbook
    With Sheet1.ListBox1
        .AddItem "East"
        .AddItem "West"
        .AddItem "South"
        .AddItem "North"
    End With
    
End Sub

Output:

Here is the screen-shot of the ListBox with items.
listbox in excel vba -AddItems

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 the see the Items in ListBox1
Move all Items from ListBox1 to ListBox2

You can move the items from one ListBox to another ListBox. It is helpful while developing tools. You can give provide the users to select items and add into another ListBox.

Code:
Private Sub cmdMoveAllRight_Click()
    
    'Variable Declaration
    Dim iCnt As Integer
    
    'Move Items from ListBox1 to ListBox2
    For iCnt = 0 To Me.ListBox1.ListCount - 1
        Me.ListBox2.AddItem Me.ListBox1.List(iCnt)
    Next iCnt
    
    'Clear ListBox1 After moving Items from ListBox1 to ListBox2
    Me.ListBox1.Clear
    
End Sub
Output:

Here is the screen-shot to show you moving the items from one ListBox to another.
listbox in excel vba-Move Listbox1 Items to ListBox2

Instructions:
  1. Please follow the above mentioned design steps
  2. Double Click on the 1st button or Right Click on 1st button and then click on View Code
  3. Copy the above code and Paste in the code window
  4. Goto Sheet1 and then Click on “>>” button
  5. Now all ListBox1 Items are available in ListBox2
  6. Save the file as macro enabled workbook
Move all Items from ListBox2 to ListBox1

The following example will show you how to move all items in on-shot from one ListBox to another ListBox.

Code:
Private Sub cmdMoveAllLeft_Click()
    
    'Variable Declaration
    Dim iCnt As Integer
           
    'Move Items from ListBox1 to ListBox2
    For iCnt = 0 To Me.ListBox2.ListCount - 1
        Me.ListBox1.AddItem Me.ListBox2.List(iCnt)
    Next iCnt
    
    'Clear ListBox1 After moving Items from ListBox1 to ListBox2
    Me.ListBox2.Clear
    
End Sub
Output:

Here is the sample screen-shot.
listbox in excel vba-Move Listbox2 Items to ListBox1

Instructions:
  1. Please follow the above mentioned design steps
  2. Double Click on the 4th button or Right Click on 4th button and then click on View Code
  3. Copy the above code and Paste in the code window
  4. Goto Sheet1 and then Click on “<<» button
  5. Now all ListBox2 Items are available in ListBox1
  6. Save the file as macro enabled workbook
Move selected Items from ListBox1 to ListBox2

You can move only selected items form One ListBox to another ListBox. See the below example…

Code:
Private Sub cmdMoveSelLeft_Click()
    
    'Variable Declaration
    Dim iCnt As Integer
        
    'Move Selected Items from Listbox1 to Listbox2
    For iCnt = 0 To Me.ListBox2.ListCount - 1
        If Me.ListBox2.Selected(iCnt) = True Then
            Me.ListBox1.AddItem Me.ListBox2.List(iCnt)
        End If
    Next
    
    For iCnt = Me.ListBox2.ListCount - 1 To 0 Step -1
        If Me.ListBox2.Selected(iCnt) = True Then
            Me.ListBox2.RemoveItem iCnt
        End If
    Next
    
End Sub
Output:

Here is the sample screen-shot.
listbox in excel vba-Move Selected Items from Listbox1 to ListBox2-Example

Instructions:
  1. Please follow the above mentioned design steps
  2. Double Click on the 2nd button or Right Click on 2nd button and then click on View Code
  3. Copy the above code and Paste in the code window
  4. Goto Sheet1 and selct items from ListBox1, Which we want to move to ListBox2
  5. Click on “>” button
  6. Now ListBox1 selected Items are available in ListBox2
  7. Save the file as macro enabled workbook
Move selected Items from ListBox2 to ListBox1

You can move only selected items form One ListBox to another ListBox. See the below example…

Code:
Private Sub cmdMoveSelRight_Click()
    
    'Variable Declaration
    Dim iCnt As Integer
        
    'Move Selected Items from Listbox1 to Listbox2
    For iCnt = 0 To Me.ListBox1.ListCount - 1
        If Me.ListBox1.Selected(iCnt) = True Then
            Me.ListBox2.AddItem Me.ListBox1.List(iCnt)
        End If
    Next
    
    For iCnt = Me.ListBox1.ListCount - 1 To 0 Step -1
        If Me.ListBox1.Selected(iCnt) = True Then
            Me.ListBox1.RemoveItem iCnt
        End If
    Next
    
End Sub
Output:

listbox in excel vba-Move Selected Items from Listbox2 to ListBox2-Example

Instructions:
  1. Please follow the above mentioned design steps
  2. Double Click on the 3rd button or Right Click on 3rd button and then click on View Code
  3. Copy the above code and Paste in the code window
  4. Goto Sheet1 and selct items from ListBox2, Which we want to move to ListBox1
  5. Click on “<» button
  6. Now ListBox2 selected Items are available in ListBox1
  7. Save the file as macro enabled workbook
Clear ListBox Items

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

Code:
Sub Clear_ListBox()
    
    'Clear ListBox Items
    With Sheet1
        .ListBox1.Clear
        .ListBox2.Clear
    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 ListBox items before loading items to ListBox
  6. It will clear items from ListBox
  7. Save the file as macro enabled workbook
Select Multiple Items from ListBox

The following example will show selecting multiple items.

Code:
Sub SelectMultipleItems_ListBix()

    'To Select Multiple Items in ListBox
    With Sheet1
        .ListBox1.MultiSelect = fmMultiSelectMulti
        .ListBox2.MultiSelect = fmMultiSelectMulti
    End With
End Sub
Output:

listbox in excel vba-Multiple Item Selection

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. You can call above procedure to select multiple items from ListBox
  6. You should see output as shown above
  7. Save the file as macro enabled workbook
Example File

Download the example file and Explore it.

Excel VBA ListBox Examples

Excel VBA ListBox Properties:

  • BackColor: To sets the back color of ListBox control.
  • BorderStyle: To sets the border style of ListBox control.
  • Height: To sets the height of the ListBox control.
  • Left: To sets the left position of the ListBox control.
  • MultiSelect: To select single or multiple list Items of ListBox Control.
  • TextAlign: To Align the ListBox list items.
  • Top: To sets the top position of the ListBox Control.
  • Width: To sets the width of the ListBox control.
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

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:

21 Comments

  1. Gaetan
    November 30, 2013 at 7:05 AM — Reply

    hi,

    Thanks for your example, very well written.

    I was wodnering if you could simplify the code this way ?

    Private Sub cmdMoveSelLeft_Click()

    ‘Variable Declaration
    Dim iCnt As Integer

    For iCnt = Me.ListBox2.ListCount – 1 To 0 Step -1
    If Me.ListBox2.Selected(iCnt) = True Then
    Me.ListBox1.AddItem Me.ListBox2.List(iCnt)
    Me.ListBox2.RemoveItem iCnt
    End If
    Next

    End Sub

    Or even more simplified by using one sub with parameters, parameters being the name of the controls. Somthing like this :

    Sub transfert_one_or_several_items(source As String, destination As String)
    Dim i As Integer
    For i = Controls(source).ListCount – 1 To 0 Step -1
    If Controls(source).Selected(i) Then
    Controls(destination).AddItem Controls(source).List(i)
    Controls(source).RemoveItem (i)
    End If
    Next
    End Sub

    Regards

    Gaetan
    http://www.vba101.com

  2. PNRao
    December 1, 2013 at 9:59 PM — Reply

    Hello Gaetan,
    Thanks for your suggestions. Our focus is providing fundamental concepts on VBA with proper examples to explain the use in real-time (particularly for data analysis applications).
    Yes, we can simplify the codes even further, it will be easy for advanced programs. We will provide more simpler way of writing VBA Programs and best practices in near future.

    Thanks
    PNRao!

  3. Joe
    December 27, 2013 at 5:55 AM — Reply

    Is there a way to save the selection you make? It seems, if you make a selection and save the workbook it won’t save upon re-opening (e.g. if i choose “south” then save, then I re-open, “south isn’t in Listbox2).

  4. PNRao
    December 28, 2013 at 3:54 AM — Reply

    Hi Joe,
    Excel will not save selected options in the listbox. However, you can save selected items using VBA.

    1. Put the selected option in a Range on BeforeSave Event:
    Example: in your case, we put ‘South’ in Sheet1 at Range A1

    2. Populate the Items in the Range while opening the workbook (On Workbook Open Event)
    Listbox2.value=Sheet1.Range(“A1”)

    Hope this clarifies your doubt.

    Thanks-PNRao!

  5. Mike
    January 22, 2014 at 6:21 AM — Reply

    Hi!

    this is very helpful for a starter like me..
    Im just wondering on how to code if i want to fill the list box by values which is in another sheet in a column.
    this is for easy maintenance. Not hardcoding all the needed values.

    Thanks,
    Mike

  6. PNRao
    January 22, 2014 at 11:28 PM — Reply

    Hi Mike,

    You can do this in two different ways.

    1. Without using VBA: Place a listbox form control (Not an activeX Control)in your worksheet. Then right click on it and choose the input range to fill the items in the listbox.
    (To insert listbox: Goto Developer Tab in the ribbon => under developer tab click on the Insert in the Controls group under)

    2. Using VBA: Loop through the range using for or do while loop and add the item to an activex listbox:
    place a listbox (activex control) in your worksheet, let’s assue you have placed a listbox (ListBox1) in Sheet1. And you have the the data in Sheet2 for Range A1 to A10. The following procedure will populate the list box, you can call this in the workbook open event.

    Sub populateListbox()
    Sheet1.ListBox1.Clear
    For i = 1 To 10
    Sheet1.ListBox1.AddItem Sheet2.Cells(i, 1)
    Next
    End Sub

    Hope this helps.
    Thanks-PNRao!

  7. Jov
    February 25, 2014 at 6:46 AM — Reply

    Hi, This is very help like me as newbie. what if i have a userform with 3 textboxes which i want to fill the listbox using textboxes data.

    Thanks

    Jov

  8. PNRao
    February 25, 2014 at 11:20 PM — Reply

    Hi Jov,
    Thanks for your comments.
    You can use same method like:


    ListBox1.Clear
    ListBox1.AddItem TextBox1.Value
    ListBox1.AddItem TextBox2.Value
    ListBox1.AddItem TextBox3.Value

    if you have many textboxes, you can do something like below:

    ListBox1.Clear
    For iCntr=1 to 10
    ListBox1.AddItem Me.Controls("TextBox" &iCntr).Value
    Next

    Hope this helps!
    Thanks
    PNRao

  9. Erin
    June 23, 2014 at 11:05 PM — Reply

    I followed excatly all of the steps as outlined – and although my items move between for the “all” buttons they do not move for the “select” buttons. Is there something else I can do for the “select” buttons? Thanks.

  10. Alex
    August 4, 2014 at 10:47 PM — Reply

    Hi,
    I may have two problems with the code you’re providing.
    First with this line:
    Me.ListBox1.RemoveItem iCnt
    There, VBA’s always giving me an error.

    Second with the saving of the values:
    I’m using a range for my listbox values so they can be save. In fact, all the items in my list that are selected are being send to cells and when I reopen, I use ListFillRange to repopulate my ListBox. The problem is that I would like to modify my selection after reopening the file and VBA won’t allow it because the ListBox can’t be clear.

  11. PNRao
    August 17, 2014 at 11:48 AM — Reply

    Hi Alex,

    It should work fine, could you please provide me the example file.

    Thanks-PNRao!

  12. Thadak
    September 17, 2014 at 2:03 AM — Reply

    Hi,
    Thanks for your code … really helpful in our project.
    I have one question… we are hardcoding the source values in Listbox1 similarly like your code. when we select the values to Listbox2 and again when you move back that value from listbox2 to listbox1 … that value is going to last row of Listbox1. Is there any way to get display in Listbox1 as we hardcoded in the source?

  13. Nagarjuna
    November 17, 2014 at 11:37 PM — Reply

    hi,
    I am new to VBA macro and also VBA code. I have an excel sheet containing following respective columns :-Region Company, SicCode, Address, City, ZIP, ContactName, Telephone, etc………….
    Here i have to perform some data cleaning work like to eliminate exceptions from company names ( -,”,’,, @, numbers, etc.,) , SicCode exceptions ( should only contain numbers, not alphabets and no special characters), zip code exceptions ( should be in 6 characters and one space between 3 characters like “A1B 2NO”, should not be like “A1B2NO”), Contact name should be in alphabets in proper no leading and trailing spaces, telephone should be in numberic and should not contain special characters (ex: “(123) 123 1234” ).

    for all these data clean, how can i write the code and execute. pls help me in session.

  14. Hi,
    May i request you to kindly give codes and examples to change the range of listbox connected to a worksheet depending on the rows of data. i have a worksheet with 25 rows of data, which is a list of distributors. When the option to display the list is selected thru a command button to run the macro, If i added 10 more names, my listbox should display all 35 names. But, if i delete 10 names, from the original, it should display only 15 names. i.e, end range of listbox should be able to change to last row of data. To say, originally A1:A25, if 10 names added, A1:A35, if 5 names deleted then A1:A30 and so on.

  15. Bitten
    May 3, 2015 at 6:35 PM — Reply

    Hello,

    thank you Villa for this useful example. However, I noticed that there is something missing in subs called ‘cmdMoveSelLeft_Click()’ and ‘cmdMoveSelRight_Click()’. I mean, when you select the last item on the list (let’s it is listbox1, but the same happens with listbox2), then, while it is moved from listbox1 to listbox2, all the items are automatically removed from listbox1.

    This part of code is responsible for this situation:

    For iCnt = Me.ListBox1.ListCount – 1 To 0 Step -1
    If Me.ListBox1.Selected(iCnt) = True Then
    Me.ListBox1.RemoveItem iCnt

    End If
    Next

    I guess you should add ‘exit for’ at the end of your if-statement, so the code will look like this:

    If Me.ListBox1.Selected(iCnt) = True Then
    Me.ListBox1.RemoveItem iCnt
    Exit For
    End If

    This should solve the problem I described above.

  16. iasmer
    May 8, 2015 at 12:38 PM — Reply

    Thank You for convenient code. I use part of it for move items from left listbox to right on user form, but slightly optimise:

    ‘=== [ < ]
    ‘Move Selected Items from Listbox2 to Listbox1
    Private Sub cmb_Move_Left_Click()
    Dim iCnt%, j%
    j = 0
    iCnt = Me.lbx_NewNames.ListCount – 1
    While j ]
    ‘Move Selected Items from Listbox1 to Listbox2
    Private Sub cmb_Move_Right_Click()
    Dim iCnt%, j%
    j = 0
    iCnt = Me.lbx_OldNames.ListCount – 1
    While j <= iCnt
    If Me.lbx_OldNames.Selected(j) = True Then
    Me.lbx_NewNames.AddItem Me.lbx_OldNames.List(j)
    Me.lbx_OldNames.RemoveItem j
    iCnt = iCnt – 1
    End If
    j = j + 1
    Wend
    End Sub

    May be someone find this useful

  17. Amol
    March 11, 2016 at 2:43 AM — Reply

    If I have many controls like textbox,combobox & DTpicker then how to pull listbox items in there

    Any idea ?

    Thanks in advanced

  18. raghu
    January 10, 2017 at 1:56 PM — Reply

    multiple selection from listbox1 to listbox2 not working

  19. raghu
    January 10, 2017 at 4:45 PM — Reply

    How to copy paste columns of the list items selected in listbox???

  20. raghu
    January 10, 2017 at 4:45 PM — Reply

    How to copy paste columns of the list items selected in list box in worksheet???

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

Go to Top


Форум программистов Vingrad

Модераторы: gambit, Partizan

Поиск:

Ответ в темуСоздание новой темы
Создание опроса
> Как программно убрать выделение в listbox? 

:(

   

Опции темы



















Ответ в темуСоздание новой темы
Создание опроса
Прежде чем создать тему, посмотрите сюда:

mr.DUDA

THandle

  • Что же такое .NET? Краткое описание, изучаем.
  • Какой язык программирования выбрать? выбираем.
  • C#. С чего начать? начинаем.
  • Защита исходного кода .NET приложений, защищаем.
  • Литература по .NET, обращаемся.

  • FAQ раздела, ищем здесь.
  • Архиполезные ссылки: www.connectionstrings.com, www.pinvoke.net, www.codeproject.com

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс «транслит» если у Вас нет русских шрифтов.

Что делать если Вам помогли, но отблагодарить помощника плюсом в репутацию Вы не можете(не хватает сообщений)?
Пишите сюда, или отправляйте репорт. Поставим :)

Так же не забывайте отмечать свой вопрос решенным, если он таковым является :)


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, THandle.

 

0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Разработка Windows Forms | Следующая тема »

Like this post? Please share to your friends:
  • Excel vba pastespecial xlpastevalues
  • Excel vba listbox select items
  • Excel vba pastespecial all
  • Excel vba listbox scrollbars
  • Excel vba paste image