vb6backspacectrl

Ctrl+Backspace in VB6?


I use the following VB6 code to Ctrl+Backspace words, but it only works if the words are separated by spaces. I need it to work if the words are separated by any special character: . - #, etc.

Public Sub DelLastWord(tb As TextBox)
    Dim WordStart As String
    Dim Trimmed As String
    Dim curpos As Long

    curpos = tb.SelStart
    Trimmed = Trim$(Left$(tb.Text, curpos))
    If LenB(Trimmed) Then
        WordStart = InStrRev(Trimmed, Space$(1), Len(Trimmed))
        tb.SelStart = WordStart
        tb.SelLength = curpos - WordStart
        tb.SelText = vbNullString
    End If
End Sub

Any suggestions or code someone can give me to take care of special characters?


Solution

  • I would loop backwards from the insertion point until I found a separator character. Something like this:

    Public Sub DelLastWord(tb As TextBox)
       Dim i As Long
       Dim curpos As Long
    
       curpos = tb.SelStart
    
       For i = curpos To 1 Step -1
          If isSeparator(Mid(tb.Text, i, 1)) Or i = 1 Then
             tb.SelStart = i - 1
             tb.SelLength = curpos - i + 1
             tb.SelText = vbNullString
             Exit Sub
          End If
       Next
    End Sub
    
    Private Function isSeparator(char As String) As Boolean
       'if the character is not a letter or number
       'then it is a separator
    
       If Asc(char) >= 48 And Asc(char) <= 57 Then Exit Function
       If Asc(char) >= 65 And Asc(char) <= 90 Then Exit Function
       If Asc(char) >= 97 And Asc(char) <= 122 Then Exit Function
       
       isSeparator = True
    End Function