vbams-accesswhitespacesearch-box

dynamic search box not accounting for strings containing blank space


I have a dynamic search box filtering a subform based on user input. I also have a few filter buttons that filter the same subform. I set up the search box to incorporate preexisting filters applied by those buttons.

The problem:

Currently, I save the string entered into the search box as a variable I call filterText (so I don't lose the value when the form gets refreshed). After the form gets refreshed, I set the content of the search box to that saved value. Then I set the location of the insertion point to the length of the string currently in the search box (lines 9,17,18). This however, does not account for blank space. If a user types something that includes a blank space, say "Homebrew 50%", the insertion point will immediately update back to the end of the text string only and the input will end up missing the space like so "Homebrew50%". How can I get the length of the current user input including spaces?

Here the full code of my search box, there are other things wrong with it but the current question is only regarding the blank space issue:

Private Sub SearchBoxStoffe_KeyUp(KeyCode As Integer, Shift As Integer)

On Error GoTo errHandler

Dim filterText As String

'Apply dynamic filter for current filter category.
If Len(SearchBoxStoffe.Text) > 0 Then
    filterText = SearchBoxStoffe.Text
    If Forms![HUB]![FilterAlleLink] = "" Then
        Me.Form.Filter = "[bezeichnung] LIKE '*" & SearchBoxStoffe & "*'"
    Else
        Me.Form.Filter = "[bezeichnung] LIKE '*" & SearchBoxStoffe & "*' AND [kategorie] = '" & Forms![HUB]![FilterAlleLink] & "'"
    End If
    Me.FilterOn = True
    'Retain filter text in search box after refreshing.
    SearchBoxStoffe.Text = filterText
    SearchBoxStoffe.SelStart = Len(SearchBoxStoffe.Text)
Else
    'Revert to current main filter category.
    If Forms![HUB]![FilterAlleLink] <> "" Then
        Call FilterStoffe("[kategorie] = '" & Forms![HUB]![FilterAlleLink] & "'")
    Else
        If Forms![HUB]![FilterAlleLink] = "" Then
            Me.Filter = ""
            Me.FilterOn = False
        End If
    End If
End If

'Set focus back to search box
SearchBoxStoffe.SetFocus

Exit Sub

errHandler:

MsgBox Err.Number & " - " & Err.Description, vbOKOnly, "Error ..."

End Sub

Solution

  • So, I figured out the solution eventually. When inserting the saved user input into the searchbox, you need to actually refer to the Value, not the Text of the searchbox. This will transfer any blank space in the user input correctly.

    Change line 17 to:

    SearchBoxStoffe = filterText