Ctrl+Backspace in VB6?

121 Views Asked by At

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?

2

There are 2 best solutions below

0
Brian M Stafford On BEST ANSWER

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
0
User51 On

Just replace your InStrRev call with something that finds what you want. Go to the end of the string, loop backwards, and stop at the first "special" character.

Something like this is basic, but it would do the job. I'm sure there's optimizations available, like not using the NonSpecial string and instead checking the ASCII code with math, but you get the point. This way has the benefit that it is easy to read and/or change which characters are special or not.

Public Function FindLastSpecialChar(ByVal Str As String) As Long
  Const NonSpecial As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  Dim I As Long
  
  For I = Len(Str) To 1 Step -1
    If InStr(NonSpecial, Mid(Str, I, 1)) = 0 Then
      FindLastSpecialChar = I
      Exit Function
    End If
  Next
End Function

The above returns 4 for each of the following in the immediate window:

  • ?findlastspecialchar("abc john")
  • ?findlastspecialchar("abc;john")
  • ?findlastspecialchar("abc.john")
  • ?findlastspecialchar("abc+john")