. ListBox1 (1,2,3) — мультиселект Прикрепленные файлы
Изменено: невеДимка Соколов — 14.10.2019 11:01:14 |
|
Апострофф Пользователь Сообщений: 720 |
невеДимка Соколов, вместо ListBox1_Click попробуйте ListBox1_Change |
ListBox1_Change работает только один раз. |
|
Апострофф Пользователь Сообщений: 720 |
#4 14.10.2019 12:29:15
Не допонял — что именно не работает и в чём задача? |
||
невеДимка Соколов Пользователь Сообщений: 75 |
#5 14.10.2019 13:34:00 нажимаю на 4 (ЛБ2). Нажимаю на 1(ЛБ1). выделение 4 сбрасывается
Надо чтоб сбрасывалось выделение при переходе на другой листбокс |
||
Апострофф Пользователь Сообщений: 720 |
#6 14.10.2019 13:52:14
не тогда _Enter напрашивается —
|
||||
невеДимка Соколов Пользователь Сообщений: 75 |
#7 15.10.2019 07:53:11
Почему то в родном файле так не работает, но.. если оба листбокса сделать мульти, то не снимает выделение ( снова работает один раз) Прикрепленные файлы
|
||
Апострофф Пользователь Сообщений: 720 |
#8 15.10.2019 08:59:41 невеДимка Соколов, трудно вас понять: перечитайте своё последнее сообщение внимательно.
если оба мульти, то и обработчики _Enter должны быть одинаковы?
|
||||
невеДимка Соколов Пользователь Сообщений: 75 |
#9 15.10.2019 09:33:27
Извините. |
||
Содержание
- Reset listbox selection in VBA
- 6 Answers 6
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Объект ListBox (Outlook Forms Script)
- Замечания
- Стили элемента ListBox
- События
- Методы
- Свойства
- Поддержка и обратная связь
- The Complete Guide to Excel VBA Form Control ListBoxes
- The VBA Tutorials Blog
- Table of Contents
- Introduction
- 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:
- Single — allows only one selection (xlNone).
- Multi — allows multiple selections (xlSimple).
- 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).
Источник
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.
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.
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:
In examples below I will be adding code to the Worksheet module in which I added a ActiveX ListBox control named ListBox1.
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:
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.
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
ListBox in Excel VBA – Adding, Clearing, Multiple Selection Examples
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:
- GoTo Developer Tab from Menu
- GoTo Insert from Controls Part
- Insert two ListBox’s and four Buttons from ActiveX Controls
- Select 1st Button and then Right Click Goto Properties and click on it
- Rename 1st button Name as “cmdMoveAllRight” and enter Caption as “>>”
- Select 2nd Button and Rename it as “cmdMoveSelRight” and enter Caption as “>”
- Select 3rd Button and Rename it as “cmdMoveSelLeft” and enter Caption as “<«
- Select 4th Button and Rename it as “cmdMoveAllLeft” and enter Caption as “<<«
- The final design should be as shown below
Screen Shot:
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.
Instructions:
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- From Project Explorer Double Click on ThisWorkbook
- Copy the above code and Paste in the code window
- Save the file as macro enabled workbook and Close it
- Open the file to see the output
- 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.
Instructions:
- Please follow the above mentioned design steps
- Double Click on the 1st button or Right Click on 1st button and then click on View Code
- Copy the above code and Paste in the code window
- Goto Sheet1 and then Click on “>>” button
- Now all ListBox1 Items are available in ListBox2
- 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.
Instructions:
- Please follow the above mentioned design steps
- Double Click on the 4th button or Right Click on 4th button and then click on View Code
- Copy the above code and Paste in the code window
- Goto Sheet1 and then Click on “<<» button
- Now all ListBox2 Items are available in ListBox1
- 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.
Instructions:
- Please follow the above mentioned design steps
- Double Click on the 2nd button or Right Click on 2nd button and then click on View Code
- Copy the above code and Paste in the code window
- Goto Sheet1 and selct items from ListBox1, Which we want to move to ListBox2
- Click on “>” button
- Now ListBox1 selected Items are available in ListBox2
- 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:
Instructions:
- Please follow the above mentioned design steps
- Double Click on the 3rd button or Right Click on 3rd button and then click on View Code
- Copy the above code and Paste in the code window
- Goto Sheet1 and selct items from ListBox2, Which we want to move to ListBox1
- Click on “<» button
- Now ListBox2 selected Items are available in ListBox1
- 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:
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- Insert a new module from Insert menu
- Copy the above code and Paste in the code window
- We can call this procedure to clear ListBox items before loading items to ListBox
- It will clear items from ListBox
- 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:
Instructions:
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- Insert a new module from Insert menu
- Copy the above code and Paste in the code window
- You can call above procedure to select multiple items from ListBox
- You should see output as shown above
- 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.
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
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
-
Gaetan
November 30, 2013 at 7:05 AM — Replyhi,
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 IntegerFor 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
NextEnd 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 SubRegards
Gaetan
http://www.vba101.com -
PNRao
December 1, 2013 at 9:59 PM — ReplyHello 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! -
Joe
December 27, 2013 at 5:55 AM — ReplyIs 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).
-
PNRao
December 28, 2013 at 3:54 AM — ReplyHi 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 A12. 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!
-
Mike
January 22, 2014 at 6:21 AM — ReplyHi!
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 -
PNRao
January 22, 2014 at 11:28 PM — ReplyHi 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 SubHope this helps.
Thanks-PNRao! -
Jov
February 25, 2014 at 6:46 AM — ReplyHi, 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
-
PNRao
February 25, 2014 at 11:20 PM — ReplyHi 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 -
Erin
June 23, 2014 at 11:05 PM — ReplyI 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.
-
Alex
August 4, 2014 at 10:47 PM — ReplyHi,
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. -
PNRao
August 17, 2014 at 11:48 AM — ReplyHi Alex,
It should work fine, could you please provide me the example file.
Thanks-PNRao!
-
Thadak
September 17, 2014 at 2:03 AM — ReplyHi,
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? -
Nagarjuna
November 17, 2014 at 11:37 PM — Replyhi,
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.
-
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. -
Bitten
May 3, 2015 at 6:35 PM — ReplyHello,
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 iCntEnd If
NextI 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 IfThis should solve the problem I described above.
-
iasmer
May 8, 2015 at 12:38 PM — ReplyThank 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 SubMay be someone find this useful
-
Amol
March 11, 2016 at 2:43 AM — ReplyIf I have many controls like textbox,combobox & DTpicker then how to pull listbox items in there
Any idea ?
Thanks in advanced
-
raghu
January 10, 2017 at 1:56 PM — Replymultiple selection from listbox1 to listbox2 not working
-
raghu
January 10, 2017 at 4:45 PM — ReplyHow to copy paste columns of the list items selected in listbox???
-
raghu
January 10, 2017 at 4:45 PM — ReplyHow to copy paste columns of the list items selected in list box in worksheet???
Effectively Manage Your
Projects and Resources
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.
Page load link
Go to Top
Форум программистов Vingrad
Модераторы: gambit, Partizan |
Поиск: |
|
Как программно убрать выделение в listbox? |
Опции темы |
|
Прежде чем создать тему, посмотрите сюда: | |
|
Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс «транслит» если у Вас нет русских шрифтов. Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, THandle. |
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
0 Пользователей: |
« Предыдущая тема | Разработка Windows Forms | Следующая тема » |