Could not set the List property - excel

I have looked for this issue and actually tried to follow some of the solutions but it happens that for some reason it's not working with me.
So I have a dropdown menu (gateway) and a text box (dueDate) and once I select and fill the blank spaces I want to populate a ListBox1 being the 1st column the gateway and 2nd column the dueDate.
this is what I have, but it pops up a window saying:
"Run-time error '381':
Could not set the List property. Invalid property array index."
Private Sub CommandButton2_Click()
'ListBox1.AddItem (gateway.Value)
ListBox1.List(ListCount - 1, 0) = gateway.Value
ListBox1.List(ListCount - 1, 1) = dueDate.Value
End Sub
I have set the ListBox1 BoundColumn and ColumnCount to 2 in the design editor.
Thanks in advance!
EDIT:
Managed to fix it. Based on the first comment to this thread I have used the following.
With ListBox1
ListCount = .ListCount
.AddItem gateway.Value
.List(ListCount, 1) = dueDate.Value
End With

I needed some time to figure this out myself (^.^):
Private Sub CommandButton2_Click()
With ListBox1
ListCount = .ListCount
.AddItem gateway.Value, ListCount -1
.List(ListCount - 1, 0) = dueDate.Value
End With
End Sub
Tell me if it worked.

Related

How do I get the ListIndex of an Item in a Combobox when I have the Value, so I can remove the Item from a ListBox with the same list?

I have a Listbox SkuList whose list is equal to the list of a seperate Combobox SkuBox. What I am trying to do, is remove the value chosen for the Combobox SkuBox from the Listbox SkuList.
Private Sub UserForm_Activate()
Dim Esh As Worksheet
Set Esh = ThisWorkbook.Sheets("Result")
Dim r_sku As Range
If Esh.Range("A2") <> "" Then
For Each r_sku In Esh.Range("A2", Esh.Range("A2").End(xlDown))
Me.SkuBox.AddItem r_sku.Value
Next r_sku
End If
Me.SkuList.List = Me.SkuBox.List
End Sub
Private Sub SkuBox_Change()
Me.SkuList.List = Me.SkuBox.List
Me.SkuList.RemoveItem (SkuBox.Value)
End Sub
This last section about removing the item doesn't work, because .RemoveItem requires a ListIndex. My question is, how do I get the ListIndex of the SkuBox.Value?
You can use ListIndex, but that will not be accurate across controls. As soon as you start removing items, the indexes will be different for items in SkuList vs SkuBox.
I'm not up on my VBA, but I don't see any ID properties, so you'll need to do as stated. Loop thru and find the item by text.
The following should work, but my advice would be to get in there and play with this. If you debug and step through the code, the intellisense will give you a lot of information that you can use to discover properties and figure out how to do things.
Private Sub SkuBox_Change()
Dim selectedSkuBoxValue As String
selectedSkuBoxValue = SkuBox.Value
SkuList.ListIndex = -1
Dim listItem
For Each listItem In SkuList.List
If listItem = selectedSkuBoxValue Then
SkuList.Value = selectedSkuBoxValue
Exit For
End If
Next listItem
If SkuList.ListIndex > -1 Then
SkuList.RemoveItem SkuList.ListIndex
End If
End Sub

Moving items from Listbox1 to Listbox2 code

So, Listbox1 is populated (from another sub, linked to range of cells in the workbook) and users can select (one at a time) items from that Listbox to be shown in Listbox2, using a Command Button (Add) to move them. I've nearly managed to get it perfect. My problem is that if a user only selects the final entry in Listbox1, all other possible entries in Listbox1 are removed (blanked out/not visible/cannot be selected).
I want only the entry which has been selected from Listbox1 to be removed from Listbox1 as it appears in Listbox2.
Here's the code:
Private Sub Add_Click()
Dim i as Integer
For i = 0 To Me.ListBox1.ListCount - 1
If Me.ListBox1.Selected(i) = True Then
Me.ListBox2.AddItem Me.ListBox1.List(i)
End If
Next i
For i = Me.ListBox1.ListCount - 1 To 0 Step -1
If Me.ListBox1.Selected(i) = True Then
Me.ListBox1.RemoveItem i
End If
Next
End Sub
If there's anything obvious here, I'm really sorry. But these Listboxes have been driving me crazy for about 3 days now.
Thanks in advance
It's a single-select list, so try adding Exit For inside each loop once you've hit the selected item:
Private Sub Add_Click()
Dim i as Long
For i = Me.ListBox1.ListCount - 1 To 0 Step -1
If Me.ListBox1.Selected(i) = True Then
Me.ListBox2.AddItem Me.ListBox1.List(i)
Me.ListBox1.RemoveItem i
Exit For
End If
Next
End Sub

Excel Combo Box Refresh Dropdown?

Is there a way to refresh a combobox?
I have the following VBA code. The dropdown is populated, until the If statement where the list is cleared and populated with the matched items.
At this point, the dropdown list only shows a single item with a scroll bar. But If I close the pulldown and reopen, it's fully populated correctly.
Private Sub ComboBox_SiteName_Change()
ComboBox_SiteName.DropDown
Dim v As Variant, i As Long
With Me.ComboBox_SiteName
.Value = UCase(.Value)
If .Value <> "" And .ListIndex = -1 Then
v = Worksheets("Address").Range("Table5[[#All],[SITE NAME]]").Value
.Clear ' Clear all items
' Repopulate with matched items
For i = LBound(v, 1) To UBound(v, 1)
If LCase(v(i, 1)) Like "*" & LCase(.Value) & "*" Then
.AddItem v(i, 1)
End If
Next i
Else
' Repopulate with all items
.List = Worksheets("Address").Range("Table5[[#All],[SITE NAME]]").Value
End If
End With
End Sub
The ComboBox_Change function gets called as the user types in the combo box.. the dropdown box turns from a list into a single line with Up/Down arrows after the Clear and Repopulate matched items..
but if I close the dropdown portion and reopen it lists all the items without Up/Down arrows.
The .ListRows value = 8 by the way.
I would like a way for the dropdown potion to either close and reopen.. or a VBA function to refresh the dropdown portion, Without external buttons or controls Please
Getting the list to ONLY show values that matched the text typed by the user so far, was a nightmare. Below is what I wrote which works (but took me a while!)
Note that the MacthEntry Property of the combo box MUST be set to "2 - frmMatchEntryNone" for the code to work. (Other values cause the combo box .value property store the text of the first value that matches what the user typed, and the code relies on it storing what they typed.)
Also note, the trick to get around the behaviour you observed, ie the combo boxes list of values not being sized correctly, was to use the code lines:
LastActiveCell.Activate
ComboBox_SiteName.Activate
Also, the code will pick up any items on the list that have the letters typed by the user ANYWHERE in their text.
Anyway, here's my code:
Private Sub ComboBox_SiteName_GotFocus()
' When it first gets the focus ALWAYS refresh the list
' taking into acocunt what has been typed so far by the user
RePopulateList FilterString:=Me.ComboBox_SiteName.Value
Me.ComboBox_SiteName.DropDown
End Sub
' #4 Private Sub ComboBox_SiteName_Change()
Private Sub ComboBox_SiteName_Enter()
Dim LastActiveCell As Range
On Error GoTo err_Handler
Set LastActiveCell = ActiveCell
Application.ScreenUpdating = False
With Me.ComboBox_SiteName
If .Value = "" Then
' Used cleared the combo
' Repopulate will all values
RePopulateList
.DropDown
Else
' #4 reducdant
' LastActiveCell.Select
' .Activate
' ===========================================
' #4 new code
' CheckBox1 is another control on the form
' which can receive the focus and loose it without event firing
CheckBox1.SetFocus
' This will trigger the GotFocus event handler
' which will do a refresnh of the list
.SetFocus
' ===========================================
End If
End With
Application.ScreenUpdating = True
Exit Sub
err_Handler:
Application.ScreenUpdating = True
Err.Raise Err.Number, "", Err.Description
Exit Sub
Resume
End Sub
Private Sub RePopulateList(Optional FilterString As String = "")
Dim i As Long
Dim ValidValues() As Variant
' #2 range now refers to just the data cells
ValidValues = Worksheets("Address").Range("Table5[SITE NAME]").Value
With Me.ComboBox_SiteName
If FilterString = "" Then
' All all values
.List = ValidValues
Else
' #2: .List cannot be set to have no items.
' so remove all but one
.List = Array("Dummy Value")
' Only add values that match the FilterString parameter
For i = LBound(ValidValues, 1) To UBound(ValidValues, 1)
If LCase(ValidValues(i, 1)) Like "*" & LCase(FilterString) & "*" Then
.AddItem ValidValues(i, 1)
End If
Next i
' #2 add this line to remove the dummy item
.RemoveItem (0)
End If
End With
End Sub
Private Sub ComboBox_SiteName_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Application.ScreenUpdating = False
End Sub
======================================================================
You could: Replace all your code with this which should give acceptable functionality (as long a the data source is in alpha order), and it's easy! However, it doesn't quite do what you wanted.
Private Sub ComboBox_SiteName_GotFocus()
With Me.ComboBox_SiteName
.List = Worksheets("Address").Range("Table5[[#All],[SITE NAME]]").Value
End With
ComboBox_SiteName.DropDown
End Sub
Combo boxes can be set up to "filter as the user types" - so long as the data is in alphabetical order.
======================================================================
Note that in your code the following two lines cause the ComboBox_SiteName_Change event to start again. I suspect you need to add break points and debug you code more.
.Value = UCase(.Value)
.Clear ' Clear all items
Anyway, I hope this is job done.
this will be my first bounty if I get it, so please let me know if you need any more help. (I think it may be worth more than 50 points)
Harvey
================================================
PART 2:
To answer you comment issues:
(See the #2 tag in my code above)
To refer to a table column's data, excluding the header use:
=Table5[SITE NAME]
(This will be autogenerated when entering a formula if you click and drag over the data cells in a column).
The code has been altered accordlingly.
I used excel 2013 and 2010 and found that the .Activate event works in both.
See #3 for a minor change.
Please recopy all the code.
note that I introduced code to try and stop flickering using Application.ScreenUpdating, but it didn;t have any effect - I don't know why. I've left the code in so you can do further experiments should you need to.
NOTE the new procedure ComboBox_SiteName_KeyDown
================================================
PART 3:
To answer you comment issues:
It's a combo on a form ! - so make the change tagged with #4 above.
Harvey
Solved!
https://trumpexcel.com/excel-drop-down-list-with-search-suggestions/
You can do what is in the link with some modifications:
"ListFillRange" in combobox properties should be the last column (the one that is changing). If it is a userform the range will go under "RowSource".
And add this code:
Private Sub ComboBox1_Change()
Sheets("Where the data is").Range("B3") = Me.ComboBox1.Value
End Sub
Try changing the command from Change to DropButtonClick
This refreshes the list on a click of the drop down

VBA Get Combobox to 'suggest' an option

I am relatively new to VBA and I am trying to solve a problem working with a userform in Excel 2010.
I am writing a pseudo spell checker that validates words against a list. The unknown word is presented in a text box and the list of allowed words is in a combo box below. I would like the combo box to present a 'suggestion' based on the unknown word. i.e. the unknown word is "Excavation" and one of the allowed words in the combo box is "Excavate". I would like the combo box to suggest the term "Excavate". My problem is that autocomplete doesn't offer a suggestion because the unknown word is longer than the allowed word.
My thought on solving the problem is to do the following:
- Parse the unknown word into a character array.
- Add the characters one at a time to the combo box text property and allow autocomplete to run.
- As soon as autocomplete stops working, remove one character and insert the word that autocomplete suggests.
My problem is I cannot find anything to tell me once auto complete has stopped working.
Any thoughts, suggestions, or alternate approaches welcome.
Thanks in advance,
Will
You may want to change 2 properties for the ComboBox to force an entry from a list is selected:
MatchEntry --> 1 - fmMatchEntryComplete
MatchRequired --> True
So when a user try to select a word outside of the list, they get a "Invalid property value.":
This code assumes a TextBox and ComboBox as you described, still with their default names. In addition there's a button, which when pressed prompts you for a word. This word is then pasted into the textbox, which I think duplicates the behavior you're coding for:
Private Sub UserForm_Activate()
With Me.ComboBox1
.AddItem "bat"
.AddItem "battleship"
.AddItem "battle"
.AddItem "batty"
.AddItem "bathhouse"
End With
End Sub
Private Sub CommandButton1_Click()
Me.TextBox1 = Application.InputBox("Word", , , , , , , 2)
End Sub
Private Sub TextBox1_Change()
Dim WordToMatch As String
Dim AvailableWords() As String
Dim i As Long
Dim MatchedWordPosition As Long
Dim LongestWordLength As Long
With Me.ComboBox1
.ListIndex = -1
WordToMatch = Me.TextBox1.Text
ReDim AvailableWords(0 To .ListCount - 1)
For i = LBound(AvailableWords) To UBound(AvailableWords)
AvailableWords(i) = .List(i)
LongestWordLength = WorksheetFunction.Max(Len(.List(i)), LongestWordLength)
Next i
For i = 0 To Len(WordToMatch) - 1
On Error Resume Next
MatchedWordPosition = WorksheetFunction.Match(WordToMatch & WorksheetFunction.Rept("?", (LongestWordLength - Len(WordToMatch)) - i), AvailableWords(), 0)
If MatchedWordPosition > 0 Then
Exit For
End If
Next i
If MatchedWordPosition > 0 Then
.ListIndex = MatchedWordPosition - 1
End If
End With
End Sub
I imagine there are a few ways to skin this cat, but this is my best effort.

VBA Excel combobox not displaying the value after selecting option

Private Sub ComboBox1_DropButtonClick()
If ComboBox1.ListCount > 0 Then
ActiveSheet.ComboBox1.Clear
End If
For N = 1 To ActiveWorkbook.Sheets.Count - 1
ComboBox1.AddItem ActiveWorkbook.Sheets(N).Name
Next N
End Sub
I'm new to VBA so please bear with me. I may not be doing this the best way to begin with.
The code is taking the names of each sheet in my workbook (with the exception of the last sheet) and adding them to a combobox list. At first, each time I clicked the drop down, all sheet names were being added again making the list continue to grow with every click. My remedy was to clear the combobox first on each click and repopulate.
However, with the clear option being used, the value is not being displayed when making my selection. It displays fine when not using the clear option. Everything else still works, but I need it to show the selected value so users aren't confused.
Is there a better way to accomplish what I need?
EDIT: If it matters, this is not in a user form, it's just a active x combobox located directly on a worksheet.
this is a very strange behavior - but the DopButtonClick event is triggered again when you select the item in the list. Therefore, the value that was just assigned get cleared upon the .Clear in the second run.
This code fixes it:
Private Sub ComboBox1_DropButtonClick()
Dim strValue As String
Dim n As Integer
strValue = ComboBox1.Value
If ComboBox1.ListCount > 0 Then
ActiveSheet.ComboBox1.Clear
End If
For n = 1 To ActiveWorkbook.Sheets.Count - 1
ComboBox1.AddItem ActiveWorkbook.Sheets(n).Name
Next n
ComboBox1.Value = strValue
End Sub
Something like below would work. However, I'd question why you'd want to repopulate the combobox everytime someone clicks on it. Why not do it when the workbook opens or the worksheet is activated?
Private Sub ComboBox1_DropButtonClick(ComboBox1 As ComboBox)
Dim strSelected As String
If ComboBox1.ListIndex > -1 Then
strSelected = ComboBox1.List(ComboBox1.ListIndex)
End If
If ComboBox1.ListCount > 0 Then
ActiveSheet.ComboBox1.Clear
End If
For N = 1 To ActiveWorkbook.Sheets.Count - 1
ComboBox1.AddItem ActiveWorkbook.Sheets(N).Name
If strSelected = ActiveWorkbook.Sheets(N).Name Then
ComboBox1.ListIndex = N - 1
End If
Next N
End Sub
Very nice solution Peter.
In my case I have a list of items that can change between two combobox runs. If the selected combobox item is not anymore in the combo list, at the next run, the line:
ComboBox1.Value = strValue
throws an error .
I've found that declaring a public index:
Public nr As Integer
and making a count inside the combobox code in order to run .clear only once per button action makes this working independently of the list update:
Private Sub ComboBox1_DropButtonClick()
Dim n As Integer
If nr = 0 Then
ActiveSheet.ComboBox1.Clear
nr = 1
Else
nr = 0
End If
For n = 1 To ActiveWorkbook.Sheets.count - 1
ComboBox1.AddItem ActiveWorkbook.Sheets(n).Name
Next n
End Sub

Resources