Clearing a list box and any selected items in list - excel

I have an Excel VBA application that goes through a sheet which contains product orders on a sheet in a workbook and searches the worksheet for orders that match various criteria which is populates in a search worksheet. The contents from this worksheet are then displayed in list box. There are several user forms that allow the user to select an order and then manipulate the order. After doing this the order manipulated may not meet the search criteria so I want to clear the list box contents and the selected row in the list box. I have tried numerous things but nothing seems to work. My latest is something list this:
Private Sub ClearListBox()
UserForm5.lstOpenO.ListIndex = -1
UserForm5.lstOpenO.RowSource = ""
End Sub
But I have tried setting the UserForm5.lstOpenO.Selected to false for all the rows. I have tried clearing the search worksheet and then displaying that which should only show the headers on the columns but the highlight in the selected row remains.
Any help would be greatly appreciated
Bruce

First of all you should not use the default instance of the userform in your code. This will lead to ambigous behaviour
I'd suggest
Private Sub ClearSelectionInListBox()
Dim varItm as variant
With lstOpen0
varItm = .MultiSelect
.MultiSelect = 0
.MultiSelect = 1
.MultiSelect = varItm
End With
End Sub
This will clear the selection within the listbox.
It is not clear if you really want to clear the contents. Because if you want then it does not make sense to think about clearing the selection.
If you want to clear the listbox then it is not neccessary to clear the selection first.
Private ClearListBox()
With lstOpen0
.RowSource = ""
.Clear
End With
End Sub
But after that you need to fill the listbox again.
Further reading
VBA userform
Userform.Show
ListBox

Related

Removing the row highlight from selected row in a list box

Working on my first Excel VBA project so very new. The application keeps track of inventory, orders, and legal information that has to be associated with an order. The application has multiple user forms that handle various state changes as inventory is added and orders are processed. In particular there is a different user form for each thing the user must do to move an order along.
I have some code that dynamically searches through a worksheet to find orders in a worksheet that are in a particular state. I populate the search results in a different spreadsheet.
The user can then select an order and perform the steps to advance it along the process. I display the search results to the user using the RowSource property.
After the user has made a selection and processed the order, I want to return to the user form to process other orders in the same state. So, I clear the form and redo search and display the results. But when I do this the original selected row in the list box is still highlighted.
I want to clear this highlight when I repopulate the list box. I am clearing the list box and repopulating it but the highlight on the selected row remains and I cannot seem to remove it.
Here is what it looks like:
I have tried several things and here is my current code but none of this works
Private Sub ClearListBox()
Dim varItm As Variant
' Me.lstOpenO.Clear
' Me.lstOpenO.ListIndex = 0
Me.lstOpenO.Value = ""
Me.lstOpenO.ListIndex = -1
Me.lstOpenO.RowSource = ""
With lstOpenO
varItm = .MultiSelect
.MultiSelect = 0
.MultiSelect = 1
.MultiSelect = varItm
End With
End Sub
I saw in another post that you can unload a user form. I tried putting this code in the ClearList subroutine (see below). When I do this each time, I execute the load command it executes the Initialize Userform5 subroutine. So, it gets into an infinite loop. I tried declaring a public Boolean variable to prevent this but every time I load the User Form the variable gets reset. Is there some way to make this work.
Private Sub ClearListBox()
Unload UserForm5
Load UserForm5
End Sub
Thanks for any help you can give.
If it's a Multiselect listbox, you need to loop through the Selected item array.
Dim x As Integer
For x = 0 To lstOpenO.ListCount - 1
lstOpenO.Selected(x) = False
Next
*braX Thanks! *
My list box is a single selection but based on your answer I tried this. This list box is being filled from a worksheet called "Search" so first I cleared this and filled the list box with only the headers. The I changed my list to be multiselect
and used your code to clear the selection. The end result is the highlight is cleared as are the contents of the list.
' Clear search worksheet
NRow = [Counta(Search!A:A)] ' identify last row
For iRow = 2 To NRow
For Column = 1 To 12
Sheets("Search").Cells(iRow, Column) = ""
Next
Next
'Clear list box
Me.lstOpenO.RowSource = "Search!A2:L2"
Me.lstOpenO.MultiSelect = fmMultiSelectMulti
For x = 0 To lstOpenO.ListCount - 1
lstOpenO.Selected(x) = False
Next
Me.lstOpenO.MultiSelect = fmMultiSelectSingle

How to generate a copy of a page from a drop down menu in Excel?

I am developing an electronic audit sheet for work, where the desire is to generate a new work sheet each day, copied from a blank master sheet. This part is easy, I have a simple macro attached to a button that generates a copy of my master sheet, places it last in the tab, and automatically names it the current day's date.
Sub NewDay()
Sheets("Master").Copy After:=Worksheets(Worksheets.Count)
NewPageName = Format(Date, "dd-mm-yyyy")
ActiveSheet.Name = NewPageName
End Sub
What I would now like to do is to give the ability to create a new sheet from a selection of 'master' sheets, while retaining the date-as-sheet-name part.
Ideally, the user experience would be to select from a drop down menu the sheet, and click a button to create the new sheet, or to click the button, be presented with the list of options to select, and then generate.
I am relatively inexperienced at VBA, and this is beginning to go out of what little realm of mastery I have. Any and all help would be greatly appreciated.
For selecting items from a list in a User form, I strongly recommend ComboBox. In Project Explorer, insert a userform, and add a ComboBox and a Button. To create the list for the user to select from. We need to have our macro do ComboBox.Add(SheetName,Index) for each of the Master Sheets. To keep track of everything, it's best to have them declared in an array.
We then pop-up the form for the user to interact with using UserForm.Show. Once the user has made their selection, the select button does UserForm.Hide to close the form.
Since we created the combobox list from an array, the list index of the selected item is equivalent to the array index of the sheet we want to copy.
Sub Start()
Dim MasterSheets() As Variant, ShtSelect As Integer
MasterSheets = Array(Sheet1, Sheet2, Sheet3, Sheet4)
'This is your list of Master Sheets.
'Change Sheet1 and Sheet2 to Sheets("Master1") and Sheets("Master2")
With UserForm1
.ComboBox1.Clear
For i = LBound(MasterSheets) To UBound(MasterSheets)
.ComboBox1.AddItem MasterSheets(i).Name, i
Next i
.Show
ShtSelect = .ComboBox1.ListIndex
'This is how to get the user selected item from the ComboBox
End With
'The Selected Sheet is referenced by MasterSheets(ShtSelect)
'Your code from before
MasterSheets(ShtSelect).Copy After:=Worksheets(Worksheets.Count)
NewPageName = Format(Date, "dd-mm-yyyy")
ActiveSheet.Name = NewPageName
End Sub
These are the only lines inside UserForm1
Private Sub CommandButton1_Click()
If UserForm1.ComboBox1.ListIndex <> -1 Then Me.Hide
'ListIndex = -1 means that the user has not yet selected anything.
End Sub
You may also want to check to see if a sheet with that name already exists before attempting to create it. Otherwise you may run into errors if someone runs the macro twice in one day.
I would suggest something like:
NewPageName = Format(Date, "dd-mm-yyyy")
If Sheets(NewPageName) Is Nothing Then 'Only copy if it doesn't already exist
MasterSheets(ShtSelect).Copy After:=Worksheets(Worksheets.Count)
ActiveSheet.Name = NewPageName
End If

Detect ComboBox Change Excel VBA

I have a sheet with a bunch of ComboBoxes(form control) and I want to detect when a user changes any one of them and write text in a cell. Using Worksheet_Change on the target cells doesn't work. I have tried a bunch of things that don't work. I'm not sure what needs to be in the private sub line or the if statement.
Private Sub DropDowns_DropButtonClick()
If ActiveSheet.DropDowns.Value > 1 Then
Cells(13, 5).Font.Bold = True
Cells(13, 5).Font.Color = vbRed
Cells(13, 5).Value = "!!! Selections have been changed. !!!"
End If
End Sub
I have tried
ComboBox_AfterUpdate()
ComboBox_Change()
DropDowns_AfterUpdate()
DropsDowns_Change()
and anything else I could find. I've also tried a few different things in the if statement with no luck.
I appreciate any help.
Chris
If I'm reading you correctly, you're comboboxes are in a userform. If I'm correct, simply open your userform in 'Visual Basic' and double click on the relavant combobox. This will open the code pane and create an empty Private Sub routine called 'Private Sub <Combobox Name> ()'.
Enter your code to place your data in the sheet (or whatever else you want) into the subroutine and Bob should be your uncle.
Apologies in advance if there's something I've missed.
RannochRob
Edit...
OK, my mistake, it's a form control.
My first comment is that it's easier to use an activex control if you can... however, with a form control, should (a) Use the cell link box in the 'Format Control' drop down ('Control' tab) to place the result in a cell... however, that result will not be the content of the box but an integer equal to the position of the selected entry on the list of entries in the combobox. You then need to (b) assign a macro to the combobox which will pick up the result and use it to get the required information from the range containing the list of entries. Like I say, much easier with an activex control...
RannochRob
Here's how you can do it by assigning a macro to the combobox (right click on the combobox>assign macro) as #BigBen mentioned in the comments section:
Option Explicit
Sub DropDown1_Change()
Dim sht As Worksheet
Dim dd As DropDown
Set sht = ThisWorkbook.Worksheets("Name of your Worksheet") 'Name of the worksheet in which the combobox is located
Set dd = sht.DropDowns("Drop Down 1") 'name of your combobox
sht.Range("G1").Value = "The selected value is: " & dd.List(dd.Value) 'dd.value returns the index of the selected value
End Sub
You can use the same code for each one of your comboboxes.
For demonstration purposes i have used the following set-up:
You can easily modify the code to best fit your needs.

Auto populate Combobox from range

I am using Excel 2013 and I have written the below code to auto populate a combobox from a range for one of my userforms. I have the combobox named "Times"
Sometimes this populates the list and other times it gives a blank list even though the range did not change.
Any idea how to stop this and just have it work everytime?
Private Sub UserForm_Initialize()
Sheets("Backend").Visible = xlSheetVisible
Times.RowSource = Sheets("Backend").Range("E1:E96").Address
Sheets("Backend").Visible = xlVeryHidden
End Sub
I have found a different way to do this now that works. Thanks to this post.
Populate list box with a named range

excel vba: show message on dropdown list selection change if changed more than once?

I am trying to create a piece of vba code which will generate a message to the user when a user selects a value from a dropdown list/validation list in excel.
So far my script does this fine. However, I want the user to be able to select their first value from the dropdown list without getting a message, and then on the second, third or fourth time etc, if they should change their selection in the dropdown list I want the message to display.
Can someone please show me a way of doing this? Thanks in advance
'Check number of times a user has changed their selection
Dim rM As Range
Set rM = Range("M" & ActiveCell.Row).Cells.SpecialCells(xlCellTypeAllValidation)
If Intersect(Target, rM) Is Nothing Then
Else
MsgBox "changed"
End If
Add ..
Private BooRangeSelected as Boolean
... at the very top of the VBA code.
Set this value to False in the Initialize event.
Set this value to True when the dropdown list is updated.
If the value is already True when the dropdown list is selected then issue the message.
I'm assuming this macro is attached to a Workbook rather than a Form stored in "personal.xlsb". In Excel / view code double click the "ThisWorkbook" icon (see below
Private Sub Workbook_open()
Private BooRangeSelected as Boolean
BooRangeSelected = False
End Sub
This sets the variable to False once the Worksheet is opened. You can then set this to True once the dropdown has been selected
BooRangeSelected = True

Resources