Question

want to know the count of occurrence one word in the text box in Visual BASIC v.0.6 ? i tried to use the counter from the list but it was not good

for example: in the following sentence: " go to play and go to home"... the verb "go" appear 2 times ..then.. i want the code that count the number of occurrence of verb "go" and say to me through label for example: 2 times

for example: in the following sentence: " go to play and go to home"... the verb "go" appear 2 times ..then.. i want the code that count the number of occurrence of verb "go" and say to me through label for example: 2 times

Was it helpful?

Solution 2

Try the following code: -

Dim txt$, find$, i1%, count%

txt = "go to play and go to home"
find = "go"

i1 = 0
Do
    i1 = InStr(i1 + 1, txt, find)
    If i1 > 0 Then
        count = count + 1
        i1 = i1 + Len(find)
    Else
        Exit Do
    End If
Loop

MsgBox count

OTHER TIPS

You can use replace() to remove the word from the string, and then compare the length resulting string with the length of the original string, and devide that by the length of the word

Option Explicit

Private Sub Command1_Click()
  Label1.Caption = CStr(CountWord(Text1.Text, "go")) & " times"
End Sub

Private Sub Form_Load()
  Text1.Text = " go to play and go to home"
End Sub

Private Function CountWord(strText As String, strWord As String) As Long
  CountWord = (Len(strText) - Len(Replace(strText, strWord, ""))) / Len(strWord)
End Function

the function CountWord above finds the amount of strWord in strText, it doesn't search for separate words, but also adds one to the count if strWord is part of a larger word

For example " go to play and go to home to search on google" would count 3 instances of "go"

You can use regular expressions to count word occurrences

Private Sub Form_Load()
    Debug.Print CountWords(" go to play and G.O to home to search on g.o" & vbCrLf & "ogle", "g.o")
End Sub

Private Function CountWords(sText As String, sWord As String) As Long
    Dim sPattern            As String

    sPattern = pvInitRegExp("[-[\]{}()*+?.,\\^$|#\s]").Replace(sWord, "\$&")
    CountWords = pvInitRegExp("\s" & sPattern & "\s").Execute(sText).Count
End Function

Private Function pvInitRegExp(sPattern As String) As Object
    Set pvInitRegExp = CreateObject("VBScript.RegExp")
    With pvInitRegExp
        .Pattern = sPattern
        .Global = True
        .IgnoreCase = True
        .MultiLine = True
    End With
End Function

This takes care of word boundaries too so "google" is not counted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top