Excel VBA: Can't deselect ListBox items from listbox - excel

I have a command button that processes selected items in a ListBox (ListBox4). While i CAN deselect all the items in that command's Click() procedure, I wanted to, if the user clicked in the ListBox, to THEN deselect everything in the ListBox, prior to their selecting again.
I have code like the following, but it never seems to get called:
Private Sub ListBox4_Click()
If Apply_Format_Occurred Then
For i = 0 To ListBox4.ListCount - 1
ListBox4.Selected(i) = False
Next i
End Sub
Do i need an outside command, etc to do this? I was hoping to be able to do it like how i described.
Any help is greatly appreciated!
thanks,
Russ

You can use the GotFocus event of the ListBox so the code runs when the ListBox receives focus from the user.
Here is an example showing coding for the button and the ListBox:
Dim Apply_Format_Occurred As Boolean
Private Sub CommandButton1_Click()
'<other processes>
Apply_Format_Occurred = True
End Sub
Private Sub ListBox4_Change()
If Apply_Format_Occurred Then
For i = 0 To ListBox4.ListCount - 1
ListBox4.Selected(i) = False
Next i
Apply_Format_Occurred = False
End If
End Sub

I see this thread is old and maybe there is an easy or more elegant way to un-select a list box item. But, I figured out a way for my needs. In my case I wanted the list box to un-select only if the same item was clicked. If a new item was clicked, it would be selected as normal. I had to use two static variable (a boolean and "old selection" placeholder).
There's probably a much easier way. But, I'm new to it and and couldn't find it. Hope this helps. Setting selectedindex to -1 unselects everything. Altenatively and as effective is listboxName.ClearSelected()
Private Sub lstPendingQuotes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstPendingQuotes.Click
Static blnSelectable As Boolean = True 'use static boolean to retain value between calls
Static objOldSelected As Object = lstPendingQuotes.SelectedIndex 'use old selected in case a different index is selected
'if nothing is already selected (as in first form open) allow the selection but change boolean to false and set the OldSelected variable to the current selection
If blnSelectable Then
blnSelectable = False
objOldSelected = lstPendingQuotes.SelectedIndex
ElseIf lstPendingQuotes.SelectedIndex = objOldSelected Then 'if an item is selected and the same item is clicked un-select all and reset boolean to true for a new possible selection
lstPendingQuotes.SelectedIndex = -1 'can substitute lstPendingQuotes.ClearSelected()
blnSelectable = True
Else 'If a different index is chosen allow the new selection and change boolean to false so if the same item is clicked it will un-select
objOldSelected = lstPendingQuotes.SelectedIndex
blnSelectable = False
End If
End Sub

I had an onclick event for my listbox. I tried listbox.listindex=-1 at the end of the code in that event. It wouldn't work.
I created a separate AfterUpdate event with the single line:
listbox.ListIndex = -1
works like a charm

Related

vba both checkbox trigger and dropdown triggers does work together

i have an excel file like the following:
[enter image description here]enter image description here
[1]: https://i.stack.imgur.com/QVe6i.png
this checkbox is being controlled by a trigger and the code is as follows:
Sub CheckBox1_Click()
If Range("CheckBox1").Value = True Then
Range("ET").Rows.Hidden = True
Else:
Range("ET").Rows.Hidden = False
End If
If Range("CheckBox1").Value = True And Range("CheckBox1a").Value = True Then
Range("A50:A53").Rows.Hidden = False
Range("A61:A63").Rows.Hidden = False
Else:
Range("A50:A53").Rows.Hidden = True
Range("A61:A63").Rows.Hidden = True
End If
End sub
if the value of the checkbox is true, it hides rows "A50:A53" and"A61:A63" and unhides when the value is False. works perfect!
On the Same sheet, i have a dropdown that does the same stuff based on the selected option: following is the excel file:
[1]: https://i.stack.imgur.com/EvCt0.png
The same as the CheckBox, the dropdown option also, hides rows "A209:A210", if yes is selected. the triggers for the dropdown is as follows:
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
' Section 4. Testing part 1
If Target.Column = 53 And Target.row = 208 Then
If Target.Value = "Yes" Then
Range("Addition").Rows.Hidden = False
Range("A112:A113").Rows.Hidden = True
ElseIf Target.Value = "No" Then
Range("A112:A113").Rows.Hidden = False
Range("Addition").Rows.Hidden = True
End If
End If
End sub
The issue now is. When i start to work with the CheckBoxes, they work fine however the Dropdown doesn't respond and the same thing happens if the start to work with the dropdown, the checkboxes stop to respond.
Any suggestion or help is highly appreciated!
Instead of CheckBox1_Click try the CheckBox1_Change event. This will ensure the checkbox is updating every time the value changes, even if if doesn't gain or lose focus.
Other than that, you will need to have something in Workbook_Open that checks the default status of those checkboxes and ranges, hiding and showing rows as necessary.
You will also need a separate event just for CheckBox1a. Each CheckBox_Change script only triggers based on the named object in the script's title. For example CheckBox1_Change will only trigger for changes to a matching CheckBox1 object. So if you want things to happen when the user clicks on CheckBox1a then you need a CheckBox1a_Change script.
Finally, you are retrieving and comparing checkbox values using Range("CheckBox1") which is not intended. There is a built in method for accessing these objects through VBA. Each CheckBox is added to the Worksheet object as a member. In the sheet's code module you can write Me.CheckBox1.Value. In an external code module you could write Sheets("Sheet1").CheckBox1.Value.

Userform listbox click code does not trigger

I created a userform in Excel 2016 with two ListBoxes, using the Tools menu. I double clicked them to create subs and inserted code to check whenever one is selected.
Here is the code:
Private sub SaleType_Click ()
If SaleType.Value ="Core" then
'make sale label visible
QTDV.visible =true
' show core option btn
Core.Visible = true
End if
End sub
When I have a ListBox created from the toolbox this works, but every other time the form is run the saletype ListBox will be value null and this is a problem because I have a check to make sure the ListBox is not empty. Code follows:
If saletype = "" then
Dim msg as string Msg = " please select sale type"
Msgbox msg, and vbcritical
End if
If the ListBox presents value null it will not see it as empty and skip the check if I try saletype = null it still skips it.
I searched and it seems creating ListBoxes on the tool box is weird because Excel does not know what kind of control it is. I opted for creating the ListBoxes in VBA.
Private sub userform_initialize()
Dim saletype as msforms.Listbox
Set saletype = me.Controls.Add("Forms.ListBox.1", "SaleType")
But when running the form and selecting any option on the ListBox the SaleType_Click sub does not trigger.
If you want to implement event handling (like SaleType_Click) you need to declare the object with the WithEvents keyword:
Dim WithEvents saletype as msforms.Listbox
And if a variable/property is not set then its value doesn't exist, so instead of empty string ("") you need to validate for NULL - the IsNull function can do that (= NULL doesn't work as = only works with values):
If IsNull (saletype.Value) then
I just had a problem with my listbox_Click not being fired "every other time". Maybe it was when the same selection was desired twice in a row. Anyway, put this in the sheet code for the sheet that is "Show"ing the userform:
userformXXX.listboxYYY.ListIndex = -1
userformXXX.Show
This doesn't work if it is in the userform code.

Limit to only 1 selected checkbox

I have imported a table with check-boxes from Access to Excel. Is it possible to set the check-boxes where only one check-box can be selected from that imported table when using Excel?
In the comments Jeeped made an excellent point that radio buttons already have the functionality that you are looking for. On the other hand -- if you prefer the aesthetics of checkboxes then you can certainly use them. I created a userform with two checkboxes in a frame (and no other controls in the frame) and also included a label for displaying the chosen option. The following code deselects all other checkboxes in the frame when one is selected. I used a non-local Boolean variable to circumvent the other checkbox's event handlers while they were being changed to avoid a sort of echo effect I ran into where the events were firing when I didn't want them to (perhaps there is a less kludgy way to do that). The code easily extends to any number of checkboxes in a grouping frame.
Dim selecting As Boolean 'module level variable
Private Sub SelectOne(i As Long)
Dim c As Control
selecting = True
For Each c In Frame1.Controls
If c.Name <> "CheckBox" & i Then c.Value = False
Next c
DoEvents
Label1.Caption = i & " selected"
selecting = False
End Sub
Private Sub CheckBox1_Click()
If Not selecting Then SelectOne 1
End Sub
Private Sub CheckBox2_Click()
If Not selecting Then SelectOne 2
End Sub
I think this works best and its much easier - at least for a few boxes - for more you could write some formulas in excel and drag down then copy as values and copy paste text from excel into vba. Anyway, here it's how I did it:
I went and created code under each button - quite basic
Private Sub DateCheckBox1_Click()
If DateCheckBox1.Value = True Then
DateCheckBox2.Value = False
DateCheckBox3.Value = False
End If
End Sub
Private Sub DateCheckBox2_Click()
If DateCheckBox2.Value = True Then
DateCheckBox3.Value = False
DateCheckBox1.Value = False
End If
End Sub
Private Sub DateCheckBox3_Click()
If DateCheckBox3.Value = True Then
DateCheckBox2.Value = False
DateCheckBox1.Value = False
End If
End Sub

Assigning Excel VBA ActiveX ListBox .Selection to a TextBox

I'm trying to click a selection on an ActiveX ListBox and have value assigned to a TextBox then clear the ListBox. It seems straightforward but I'm
getting 'Object doesn't support this property or method' on the first line
This is what I'm using:
Private Sub ListBox1_Click()
ActiveSheet.OLEObjects("TextBox3").Object.Value = ActiveSheet.OLEObjects("ListBox1").Object.Selection
ActiveSheet.OLEObjects("ListBox1").Object.Selection = ""
End Sub
Any thoughts on how to make this word or resources to search are appreciated.
Your code would be cleaner written like this:
Private Sub ListBox1_Click()
TextBox1.Value = ListBox1.Text
ListBox1.Selected(ListBox1.ListIndex) = False
End Sub
But there is a problem: the second line doesn't work inside the ListBox1_Change event (because it would create an infinite loop). I tried with Application.EnableEvents = False, but it didn't help.
I think you need to put the reset of the selection in another event, like the KeyUp or MouseUp.

Troble with updating the list box

I have Created a excel user form with three Combo box and list box with 3 columns.
When user selects a value from drop down list and click Add button it will be displayed in the list box - Done
When user selects a item in the list box it will again displays in drop down list - done
But when user selects the item in the list box and click update button its calling the ListBox
_click () function, I dont want it to call the listbox_click function
PLease help. updating the code
Code for adding value from drop down list to list box
Private Sub cmdAdd_Click()
Call lstValues.AddItem(AddPpayTierOption(cboPpayTier.Value))
lstValues.List(UBound(lstValues.List), COL_BRAND) = cboBrandTier.Value
lstValues.List(UBound(lstValues.List), COL_GEN) = cboGenTier.Value
End Sub
when clicks the item in the list box it will display the value in drop down list
Private Sub lstValues_Click()
Dim I As Long
cmdEdit.Enabled = True
cmdRemove.Enabled = True
If lstValues.ListIndex <> -1 Then
For I = 0 To lstValues.ColumnCount - 1
If I = 0 Then
cboPpayTier.Value = lstValues.Column(I)
Else
If I = 1 Then
cboBrandTier.Value = lstValues.Column(I)
Else
If I = 2 Then
cboGenTier.Value = lstValues.Column(I)
End If
End If
End If
Next I
End If
End Sub
when user click the update button code.
when it goes to lstValues.Column(j) = cboPpayTier.Value line its calling the lstValues_Click() function I don't want code to call that function. Please Help
Private Sub cmdEdit_Click()
Dim j As Long
Dim var As Variant
If lstValues.ListIndex <> -1 Then
For j = 0 To lstValues.ColumnCount - 1
If j = 0 Then
lstValues.Column(j) = cboPpayTier.Value
Else
If j = 1 Then
lstValues.Column(j) = cboBrandTier.Value
Else
If j = 2 Then
lstValues.Column(j) = cboGenTier.Value
End If
End If
End If
Next j
End If
End Sub
please let me for more clarification.
Two options:
Use Application.EnableEvents = False to disable event processing. And Application.EnableEvents = True to re-enable. Note, this disables all event handling, so place it either side of code that would otherwise trigger an event you don't want.
Declare a global flag. Set it just before code that will trigger an event you don't want. In the Event Sub itself, examine the flag, and exit if it's set. Reset the flag either on the other side of the event triggering code, or in the event Sub itself. Doesn't stop the event firng, but stops it executing code you don't want.
As requested, example of option 2
In a standard module, at the top (just after Option Explicit), add this code
Global InhibitEvent As Boolean
In your code
' Somewhere in your code,
' when you are about to execute some logic that will trigger an event
InhibitEvent = True
'... event triggering logic here
InhibitEvent = False
In the Event Sub that you don't want to execute (eg a listBox Change event)
Private Sub ListBox1_Change()
' Look for Event Inhibit
If InhibitEvent Then Exit Sub
' rest of event code here
End Sub
Try using a List as the data source of list box. When updating, first put datasource of listbox null then equal to List

Resources