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
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.
You may want to change 2 properties for the ComboBox to force an entry from a list is selected:
So when a user try to select a word outside of the list, they get a "Invalid property value.":