VBA Get Combobox to 'suggest' an option

后端 未结 2 447
忘了有多久
忘了有多久 2021-01-13 16:14

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

2条回答
  •  滥情空心
    2021-01-13 16:36

    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.

提交回复
热议问题