[RESOLVED] Text Box Keypress Event problem
Hi! I'm trying to make my program count the number of words in my text box by counting the number of spaces, I tried this:
VB Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 32 Then
spacecount = spacecount + 1
End If
Label1.Caption = "Word Count:" & spacecount
End Sub
but whenever I type a non space character, it seems that spacecount is reset to 0. Oh yeah, I know the algorithm of my program for counting words is very problematic, I'll fix that later.
Re: Text Box Keypress Event problem
I think it would be better to loop through the text and get the words instead of trying to count the spaces as if they press space twice or at the beginning it will give a false count
Re: Text Box Keypress Event problem
You need to declare the spacecount variable. Either in the declarations at the top of the form, or make it static in the procedure:
VB Code:
Private iSpaceCount As Integer
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 32 Then iSpaceCount = iSpaceCount + 1
Label1.Caption = "Word Count:" & iSpaceCount
End Sub
Or:
VB Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
Static iSpaceCount As Integer
If KeyAscii = 32 Then iSpaceCount = iSpaceCount + 1
Label1.Caption = "Word Count:" & iSpaceCount
End Sub
But, yes there are several other reasons why that code won't produce the right results.
Re: Text Box Keypress Event problem
here's a little something I just knocked up:
VB Code:
Private Sub Text1_Change()
Dim N As Long, lCount As Long
Dim bSpace As Boolean, bBoolean As Boolean
Dim bytArr() As Byte
bytArr = Text1.Text
For N = LBound(bytArr) To UBound(bytArr) Step 2
bSpace = (bytArr(N) = 32) Or (bytArr(N) = 10) Or (bytArr(N) = 13)
If N > 4 Then
If ((bytArr(N) = 10) Or (bytArr(N) = 13)) And (bytArr(N - 2) = 45 Or bytArr(N - 4) = 45) Then bSpace = False
End If
If bBoolean Then lCount = lCount - (bBoolean = bSpace)
bBoolean = Not bSpace
Next N
Me.Caption = "Word Count: " & lCount - bBoolean
End Sub
Re: Text Box Keypress Event problem
Ah yes I remember about making the variable static. Thnx everyone! ;)
*marks as resolved*