How to delete multiple selections in a listbox? - vba

So I have a userform that has a:
listbox called "lstentries"
radio button called "Delete".
Also, the "Start" is the name of the cell that is the top left corner of the table of rows.
I already set the code so it can select multiple entries in the listbox. However, when I select multiple entries it only deletes the first row that it comes to. So i tried making a while loop so it keeps deleting the selected ones, but that's not working either. I get the "Run-time error '1004' - Method 'Range' of object'_Global' failed"
Hopefully someone can help me out. Here is the snippet of the code where it deletes the rows. Thanks in advance.
If optDelete.Value = True Then
Dim delete As Range
Do While True
Set delete = Range("start").Offset(lstEntries.ListIndex, 0)
delete.EntireRow.delete Shift:=xlUp
Loop
End If

In the list box you can run through the list of items. Since you are allowing for multiple items to be selected and deleted, you will have to adjust the index as items are removed.
The list box is 0-indexed which means it starts at 0 and not 1.
' set the to go through all items in the list
For listIndexCount = 0 To lstEntries.ListCount
' check to make sure the index count is not greater or equal to the total number of items
' this is needed because the ListCount will change if items are deleted
If listIndexCount >= lstEntries.ListCount Then
Exit Sub
End If
' check to see if the item is selected
If lstEntries.Selected(listIndexCount) Then
' remove item
lstEntries.RemoveItem (listIndexCount)
' subtract 1 to account for removed item
listIndexCount = listIndexCount - 1
End If
Next

Another option in cases like this is to iterate through in reverse order. When starting at the bottom of the list you do not have to worry about adjusting the index since the items further up are not affected by removing an item below them.

Related

Adding unique records to a listbox from another listbox

I am hoping someone can help me out because I don't often code in Excel VBA. I have two Listbox and a CommandButton on a UserForm, which adds selected records from the first ListBox to the second. The range in the first ListBox is kind of long and so users of the form will generally select a couple records, hit the Add button, and then scroll down the first ListBox to select more records to add. The problem is, only the ones that have been added last will actually be recognized and used to generate reports even though all of the selected records appear in the second ListBox. Here is my current code for the button that adds the records to the second ListBox:
Private Sub AddButton_Click()
For i = 0 To Listbox1.ListCount - 1
If Listbox1.Selected(i) = True Then Listbox2.AddItem Listbox2.List(i)
Next i
End Sub
How can I populate the second ListBox so that it will include every record selected no matter how many times the add button is used?

How to delete same items from multiple list box?

I am facing a problem while deleting the items from multiselect list boxes. I will try my best to explain my front end and the logic. Please let me know the correct way to get the output.
Well I need to add new subjects into a list box. I can select multiple items once added into it. I have 3 list boxes first listbox is for holding the major subjects. The second one is for holding the optional subjects. I have two text boxes that feeds the data into the list box, the items on the text box will be added when the button or enter key is pressed.
The third listbox is disabled. It takes the items from the majorsub and optsubs listbox. This means if I add 10 major subjects and 5 optional subjects then the 3rd list will hold this 15subjects. Now I can easily multi select from one list and delete it. Deleting individually is not a problem.
My concern here is - once I select the items from this two list and click delete button it has to search the same items from the third list and remove it from this list as well.
How can I do that? Please help me in this.
Add items in list 1
Remove items from list 1 and 3
This is for inserting and removing the major subs
Public Sub btnMajSubAdd_Click() Handles btnMajSubAdd.Click
Try
'CODE TO ADD MAJOR SUBJECTS IN TO THE LIST AND THE ALL SUBJECTS LIST
If btnMajSubAdd.Text = "+" Then
If txtMajSubs.Text <> "" Then
lbMajorSubs.Items.Add(Trim(txtMajSubs.Text))
lbAllSubs.Items.Add(Trim(txtMajSubs.Text))
txtMajSubs.Text = ""
txtMajSubs.Focus()
End If
Else
For n As Integer = 0 To lbMajorSubs.SelectedItems.Count - 1
' REMOVE THE CURRENT SELECTED ITEM FROM ITEMS
For i As Integer = 0 To lbAllSubs.Items.Count - 1
If lbAllSubs.Items(i).ToString = lbOptSubs.SelectedItems(n).ToString Then
lbAllSubs.Items.Remove(lbAllSubs.Items(i))
lbMajorSubs.Items.Remove(lbMajorSubs.SelectedItems(n))
i = i - 1
n = n - 1
End If
Next i
Next n
btnMajSubAdd.Text = "+"
txtMajSubs.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
The recommended way to do this is with the Model-View-Controller pattern. Instead of adding an item directly to the list box, add it to a collection, then refresh the list box with items in the collection.
In this particular case, maintain two collections, to which you add major subjects and minor subjects, respectively. On adding a new subject, you add it to the appropriate collection, then immediately refresh the list box.
Upon removing an item from the list box, remove the corresponding item from the collection, and refresh the list box again.

How to make a reset button in excel

I am trying to make a reset button that will replace any value the user has selected with the value TOTAL inside a number of comboboxes. Using the record macro i selected the combobox but i can't figure out how to insert the value. The following code gives out the 424 error.
ActiveSheet.Shapes.Range(Array("ComboBox2")).Select.Value = TOTAL
the part that i added to the macro is the .Value=TOTAL
Anyone knows what i should do? Please take note that i don't want to clear the comboboxes; I want to give them a specific value.
In case that combo boxes are Form controls use OLEFormat.Object.ListIndex to select the item.
In case that the combo boxes are ActiveX controls use OLEFormat.Object.Object.ListIndex (note in this case the first item in the list has index 0).
Then iterate through all Combo-boxes you want to reset and set ListIndex to index of item "TOTAL". In this example the item "TOTAL" is on the first place in the list so for Form Combo-box (if used) ListIndex = 1 and for ActiveX Combo-box ListIndex = 0. HTH
(You are probably using ActiveX Combo-boxes, but in the example the older Form Combo-boxes are used as well just for the case).
Sub ResetToTotal2()
Dim combos
Dim combo
Dim comboObject
combos = Array("ComboBox1", "ComboBox2", "ComboBox3")
For Each combo In combos
Set comboObject = ActiveSheet.Shapes(combo).OLEFormat.Object
If TypeName(comboObject) = "DropDown" Then
comboObject.ListIndex = 1
Else
comboObject.Object.ListIndex = 0
End If
Next combo
End Sub

Can't clear a DataGridView combobox without 100s of errors

I'm using VB.NET to make a stand-alone executable containing an unbounded DataGridView.
One of its columns is a combobox. I add rows to the combobox with some simple code
like this:
For r As Int16 = 0 To eachLine.GetUpperBound(0)
Dim dgvcbc As DataGridViewComboBoxColumn = grd.Columns(col)
' Errors: dgvcbc.Items.Clear()
dgvcbc.Items.Add(eachLine(r))
Next r
Works great the first time, but when I try to clear it, in order to add some different
items in the combobox, I get this error 100s of times:
> DataGridViewComboBoxCell value is not valid
Any ideas on how to fix this and why it occurs?
The issue is that, if you clear the Items in that column, every cell in that column becomes invalid. Every value in that column has to match one of the items in the drop-down list and, if there's no items, no value can be valid. It doesn't make sense to clear the drop-down list. You must leave at least the items that match the values in the cells of that column.

vb.net listbox- Remove ALL items that DON'T contain specific text

I'm working with a listbox in vb.net and am trying to remove all items from the listbox that don't contain specific text at the click of a button. Here's my code:
Dim i As Integer
For i = 0 To ListBoxPrePublish.Items.Count - 1
If InStr(ListBoxPrePublish.Items(i), "-8-") > 0 = False Then
ListBoxPrePublish.Items.RemoveAt(i)
Exit For
End If
Next
This only removes 1 item at a time though. How can I tweak this to remove all items that don't contain "-8-" at once?
EDIT: in case anyone asks, the listbox items list is growing rather large so I'm adding a sort feature so users can widdle down their options if they want to. That's why I'm not filtering anything before adding to the listbox
Here is the complete code for backward loop I mentioned in the comments - it should work:
For i as Integer = ListBoxPrePublish.Items.Count - 1 To 0 Step -1
If Not ListBoxPrePublish.Items(i).Contains("-8-") Then
ListBoxPrePublish.Items.RemoveAt(i)
End If
Next
No, I do not know of any RemoveRange type functionality. And be advised that you will need to loop through the listbox Items collection backwards as you remove items or you will get index exceptions, because once you remove something it will mess up the index values of all the remaining items in the iterator.