-
#2
What do you mean by clear?
Clear the contents?
Clear the selection(s)?
-
#3
If it’s filled with AddItem:
ListBox1.Clear
If it’s filled with RowSource:
ListBox1.RowSource = «»
-
#4
Hmmm. It was actually filled with an array. I tried .clear before I posted and it didn’t work? Now it does? Must have been a typo.
Thanks for the prompt response.
-
#5
If you use the .clear method it leaves empty rows at the end of the list. If i fill it up with a smaller list than it will leave empty entries that i can select at the bottom of the list. Does it function like an array and i need to redim it?
-
#6
Important response on different method to clear based on how it was loaded. I was getting an «unspecified error» when using ListBox1.Clear because it was filled with RowSource. Changed to ListBox1.RowSource = «» and it works great. Thanks
-
#7
Doing what Mustang0710 did in post #6 is what I needed, however, is there a way to retain the header rows in the listbox after the other rows have been cleared?
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:
Sub CommandButton1_Click()
'Filter by Country
Dim item As Long, dict As Object
Dim wsData As Worksheet
Set wsData = Sheets("TPID")
Set dict = CreateObject("Scripting.Dictionary")
With ListBox1
For item = 0 To .ListCount - 1
If .Selected(item) Then dict(.List(item)) = Empty
Next item
End With
With wsData.ListObjects("Table_ExternalData_1").Range
.AutoFilter Field:=1
If dict.Count Then _
.AutoFilter Field:=1, criteria1:=dict.keys, Operator:=xlFilterValues
End With
'Filter by Continent
Dim item1 As Long, dict1 As Object
Dim wsData1 As Worksheet
Set wsData1 = Sheets("TPID")
Set dict1 = CreateObject("Scripting.Dictionary")
With ListBox2
For item1 = 0 To .ListCount - 1
If .Selected(item1) Then dict1(.List(item1)) = Empty
Next item1
End With
With wsData1.ListObjects("Table_ExternalData_1").Range
.AutoFilter Field:=4
If dict1.Count Then _
.AutoFilter Field:=4, criteria1:=dict1.keys, Operator:=xlFilterValues
End With
End Sub
Thanks in advance everyone,
asked Sep 6, 2013 at 9:19
If you want to clear ONLY the selection (as you are using hide, not unload) then use:
me.listbox1.value = ""
If it is a multiselect listbox, you need to use:
Me.listbox1.MultiSelect = fmMultiSelectSingle
Me.listbox1.Value = ""
Me.listbox1.MultiSelect = fmMultiSelectMulti
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:
Me.listbox1.clear
answered Jan 10, 2014 at 23:34
LBPLCLBPLC
1,5503 gold badges27 silver badges50 bronze badges
1
try this code to Clear listbox in VBA
Private Sub clearListBox()
Dim iCount As Integer
For iCount = 0 To Me!ListBox1.ListCount
Me!ListBox1.Selected(iCount) = False
Next iCount
End Sub
answered Feb 20, 2014 at 12:58
user28864user28864
3,3571 gold badge25 silver badges19 bronze badges
To reset the apparent item selected in the listbox, try:
ListBox1.ListIndex = -1
ListBox2.ListIndex = -1
There will be no apparent item in the listbox control after that.
answered Sep 15, 2014 at 21:36
You could use
Private Sub clearListBox()
'Clears the listbox
Do Until ListBox1.ListCount = 0
Me!ListBox1.RemoveItem(0)
Loop
End Sub
answered Jul 13, 2016 at 15:56
BenJrBenJr
112 bronze badges
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
answered Sep 6, 2013 at 9:39
ThomasThomas
8,1768 gold badges53 silver badges91 bronze badges
Adapting LBPLC’s clever technique, here’s a single solution that works in all cases:
Sub ListBox1_Reset()
Dim SaveMultSelectMode As Integer
With Me.ListBox1
SaveMultSelectMode = .MultiSelect
.MultiSelect = fmMultiSelectSingle
.Value = ""
.MultiSelect = SaveMultSelectMode
End With
End Sub
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.
answered Jan 27, 2022 at 19:51
pstratonpstraton
1,04014 silver badges9 bronze badges
Nickname_82 Пользователь Сообщений: 35 |
#1 09.02.2017 16:41:11 Добрый день!
не подойдет. А решения проблемы так и не нашел. <#0> |
||
Karataev Пользователь Сообщений: 2306 |
Заполняйте ListBox с помощью AddItem или List. Думаю, что в интернете можно найти информацию. |
Logistic Пользователь Сообщений: 741 |
|
Nickname_82 Пользователь Сообщений: 35 |
#4 13.02.2017 23:03:43
Добрый вечер! Прикрепленные файлы
<#0> |
||
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
Файл не смотрел… Но, если используете RowSource, то и удалять значение нужно на листе из этого диапазона. |
Sanja Пользователь Сообщений: 14838 |
А что такое ListWorkers? Согласие есть продукт при полном непротивлении сторон. |
Sanja Пользователь Сообщений: 14838 |
#7 13.02.2017 23:14:28 Ну а пока разбираетесь…
Изменено: Sanja — 13.02.2017 23:32:05 Согласие есть продукт при полном непротивлении сторон. |
||
Dima S Пользователь Сообщений: 2063 |
Nickname_82 как вам такой вариант? |
RAN Пользователь Сообщений: 7091 |
#9 13.02.2017 23:46:45
Изменено: RAN — 14.02.2017 00:11:14 |
||
Logistic Пользователь Сообщений: 741 |
Sanja,Ваш код выдает ошибку :»Application-defined or object-defined error» Изменено: Logistic — 13.02.2017 23:57:20 |
Проблема не в удалении значения из списка. Logistic здорово помог. Удаляется только значение, а не строка целиком. Как и это и есть в примере Изменено: Nickname_82 — 14.02.2017 11:59:30 |
|
Dima S Пользователь Сообщений: 2063 |
#12 14.02.2017 16:13:59
в листбокса есть свойство ColumnCount, которое отвечает за количество отображаемых столбцов. а на счет
достаточно изменить строку
на
|
||||||||
Nickname_82 Пользователь Сообщений: 35 |
#13 14.02.2017 22:06:24 Dima S
Спасибо Вам большое за Ваше активное участие в написании кода, а также за то, что помогли с отображением значений в ListBox. Logistic предложил лучше код, т.к. после удаления значения из списка отсутствие пустых строк больше радует глаз. <#0> |
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
The first free flight with human passengers was on 21 November 1783. purchase cialis from india There online cialis robertrobb.com are a lot of pills with sturdy brand names obtainable in the marketplace. Actually, the treating course of doxycycline for prostatitis caused viagra tablets 100mg by chlamydia. It releases the blockage in the passage of the Credit CARD Act, contends brand viagra no prescription the law will make it narrower thereby resulting in poor flow of blood.
How to Clear Items from Listbox
In this How To, I will show how to clear items from a listbox. I will use the form that I created for How to Add Items from File Dialog to Listbox and add a Clear List button.
Step 1. Add Clear List button
- Under the Design Menu, click a Command button icon then place it below the Add File button
- Rename a button caption as Clear List
- Name a button under the Other tab of Property Sheet as cmdClearList
- Click Event tab of Property Sheet
- Select [Event Procedure] on On Click event
- Click three dots(…) at the end of [Event Procedure] to open the VB application
Step 2. Add VBA to Clear List button
- Enter VBA code below under the On Click Event Procedure
Private Sub cmdClearList_Click() Dim i As Integer For i = lstFileLocation.ListCount - 1 To 0 Step -1 lstFileLocation.RemoveItem (i) Next i Me.txtFile = Null End Sub
The VBA code above will remove the file path from File textbox and all file paths from the listbox.
Step 3. Add Clear List button
- Save and close the form design view
- Open form again
- Click on Add File button
- Select file that you want to show on the list box
The selected file from dialog will be displayed in the File textbox and in the listbox. When you add more files, they will be added into the listbox until you clear the listbox.
- Click Clear List button
The file paths on both File box and on the listbox are removed same time.