dcsimg
Results 1 to 30 of 30

Thread: [RESOLVED] Textbox scan of word and the word following that word

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Oct 2006
    Posts
    167

    Resolved [RESOLVED] Textbox scan of word and the word following that word

    Hello,
    I am trying to scan segments of words in a RichTextBox to alert me of potential passive voice usage. I know this is already in Word's spelling and grammar check, but I am trying to get my program to alert me when I do this.

    For example:

    "An apple was eaten by Newton" vs "Newton ate an apple"

    What I would like to do is to be able to scan text2.text (my RichTextBox) for keywords like "was", "has been", "have been" and then skip one space, and scan the following word for the endings commonly associated with the passive voice, for example "-ed, -de, -en) and so forth.

    here is what I am trying for the example above, to find the instances of the word 'was':

    If InStr(1, text2.Text, " was ") Then
    List12.AddItem "the word 'was' is in the text"
    End If


    so far so good.


    but how do you skip the space and then scan the following word for the "-en" ending of the word "eaten"?

    I know how to scan the last two letters of "eaten" if the last word in the textbox is "eaten" and there are no spaces after the "n", for example:

    List2.AddItem Right(text2.Text, 2)



    But how would I focus on the word "was", skip the space, then scan the rightmost characters of "eaten", assuming that those two words are found one after the other?

    Thank you!
    Last edited by starscrea2; Dec 25th, 2018 at 12:28 PM.

  2. #2
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    18,395

    Re: Textbox scan of word and the word following that word

    Others will give you some more insight/samples, this isn't terribly difficult: InStr() returns the position of the found text. You already know the length of the text searched. Simple math tells you where to start the next InStr(), which by the way, has a parameter to specify which character position begin searching. I don't think you are using InStr() to its max ability.

    Now, here's a flaw in your logic:

    The apple was eaten by Newton. Ok? What about: The apple was reportedly eaten by Newton.

    Edited: creating a mini word-processor from scratch is almost always a difficult task, especially if you include grammar
    Last edited by LaVolpe; Dec 25th, 2018 at 12:56 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  3. #3
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    803

    Re: Textbox scan of word and the word following that word

    In addition to the above post, you need to make sure you are properly handling the "next word"

    Examples:

    Code:
    The apple was eaten.
    The apple was eaten quickly.
    I noticed the apple was eaten, so I screamed.
    If you try to find the next word using instr to only locate where the next space character exists after " was ", you will get unexpected results.

    In the examples above, there is no space character after "eaten." in the first sentence, so the text between the space after "was" and the next located space is:

    "eaten.
    The"

    In the last sentence, you would get "eaten," in between the spaces, so to extract just the next word you need to account for carriage return/line feeds as another word delimiter, and drop all punctuation that might be include in the next "word".

    Good luck!

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Oct 2006
    Posts
    167

    Re: Textbox scan of word and the word following that word

    I agree, "the apple was reportedly eaten by Newton" would be missed by my logic.....

    Regarding the basic math
    Does this code seem like it would work?

    'Look for the word "was"
    If InStr(1, Text2.Text, "was") <> 0 Then

    ' look for the word eaten, immediately after the word "was": add 1 to the location after text2text, and see if the word after "was" ends with "-en"?

    If Right(Text2.Text + 1, 3) = "en" Then
    List2.AddItem "sequence of words triggering passive voice found"
    End If
    End If

    End Sub
    Last edited by starscrea2; Dec 25th, 2018 at 01:09 PM.

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Oct 2006
    Posts
    167

    Re: Textbox scan of word and the word following that word

    duplicate post, sorry
    Last edited by starscrea2; Dec 25th, 2018 at 01:10 PM.

  6. #6
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,929

    Re: Textbox scan of word and the word following that word

    Well the first thing you need to change is the Instr() call

    You need to capture the position returned so you can use that later

    Code:
    WordPos= InStr(1, Text2.Text, "was")
    If WordPOS>0 then
    Now you know not only it was there but where it was found. You can then use that value in your next instr() statement to locate the following word(s).
    The other statement you will need to consider is Mid$()

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Oct 2006
    Posts
    167

    Re: Textbox scan of word and the word following that word

    OK I tried the following with no result (no errors, but no response)

    Dim wordpos As Integer
    wordpos = InStr(1, text2.Text, "was")
    If wordpos > 0 Then

    If Right(wordpos + 1, 3) = "en" Then
    List2.AddItem "sequence of words triggering passive voice found"
    End If
    End If

    I'm guessing I am not moving the position correctly. Is there a specific instr tutorial people would recommend?

  8. #8
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    2,062

    Re: Textbox scan of word and the word following that word

    Hi

    this will return the postion and count "was", add the controls you see in the Code
    see if it helps
    Code:
    Option Explicit
    
    Private Sub Command1_Click()
    Text2.Text = CountStringInString(Text1.Text, "was", False)
    
    End Sub
    
    Private Sub Form_Load()
          Text1.Text = "The apple was eaten." & _
     "The apple was eaten quickly. " & _
          vbCrLf & vbCrLf & " test test " & _
            vbCrLf & " bvbvbvnvn nbvnbvnv" & _
                  vbCrLf & vbCrLf & "I noticed the apple was eaten, so I screamed."
    End Sub
    Public Function CountStringInString(Text As String, SearchFor As String, _
                                        Optional ComapareAsText As Boolean = False) As Long
    
       Dim i As Long, j As Long, z As Long
       Dim s As String, s1 As String
          If ComapareAsText Then
             s = UCase$(Text)
             s1 = UCase$(SearchFor)
          Else
             s = Text
             s1 = SearchFor
          End If
          i = 1
          Do
             j = InStr(i, s, s1, vbBinaryCompare)
           
             If j = 0 Then
                Exit Do
             End If
             i = j + Len(s1)
             'check position
               Debug.Print i & " " & s
               Debug.Print "------------------------"
               Debug.Print i & " " & s1
              
               z = z + 1
          Loop
          CountStringInString = z
    End Function
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  9. #9
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,929

    Re: Textbox scan of word and the word following that word

    Code:
    If Right(wordpos + 1, 3) = "en" Then
    That is way off.

    First of all Right() or better Right$() is for strings. wordpos is a number not a string.

    Look at how you used the 1 in your first instr() call. This is how you use the position in your next one.

    NewPos=Instr(WordPos+SomeValue,TheString,SearchFor)

    That will tell you where the next word starts but you still can't use right because that could be picking characters from 10 words later. It tests the right most part of the string and you have did nothing to isolate the part you want.

    So you need to locate the begining and the end of the word you want to check, place it into a new var and then test that for the ending, there you can use Right$().

    You can also use more than one statement within a statement but that seems a bit complex for this thread given that you do not fully understand the use of these functions.
    Another thing to consider is the Split() function You can split a string into an array of words but splitting on the space character then each word will be in a different element of the array you can then loop through the array to find your target word and check the next element for the ending you are looking for.

  10. #10
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,929

    Re: Textbox scan of word and the word following that word

    Here is a fairly basic and simple example showing how the Split() function can be used.
    Code:
    Option Explicit
    Dim TheString As String
    Private Sub Form_Load()
    TheString = "An apple was eaten by Newton"
    End Sub
    
    Private Sub Command1_Click()
    Dim strWords() As String
    strWords = Split(TheString, " ")
    Dim x As Integer
    For x = 0 To UBound(strWords)
        If strWords(x) = "was" Then
            Debug.Print "was found as word number " & x + 1 & " in the search string"
            If x < UBound(strWords) Then
                Debug.Print "Next Word is " & strWords(x + 1)
                Select Case Right$(strWords(x + 1), 2)
                    Case "en"
                        Debug.Print "Word ends in en"
                    Case "ed"
                        Debug.Print "Word ends in ed"
                    Case "es"
                        Debug.Print "Word ends in es"
                    Case Else
                        Debug.Print "Ending does not match"
                End Select
                Exit For
            Else
                Debug.Print "No words follow"
            End If
        End If
    Next
    End Sub

  11. #11
    PowerPoster
    Join Date
    Feb 2006
    Posts
    20,561

    Re: Textbox scan of word and the word following that word

    No example based on TOM?

    Code:
    Option Explicit
    
    Private Const WM_USER As Long = &H400&
    Private Const EM_GETOLEINTERFACE As Long = WM_USER + 60
    
    Private Declare Function SendMessage Lib "user32" Alias "SendMessageW" ( _
        ByVal hWnd As Long, _
        ByVal wMsg As Long, _
        ByVal wParam As Long, _
        ByVal lParam As Long) As Long
    
    'The "tom" type library is somewhat incomplete so we must define these:
    Private Const C1_SPACE As Long = &H8&
    Private Const C1_PUNCT As Long = &H10&
    
    Private TextDocument As tom.ITextDocument
    Private TextRange As tom.ITextRange
    Private KeyWords() As String
    Private TwoLetterEndings() As String
    
    Private Sub cmdNext_Click()
        Dim SentenceEnd As Long
        Dim SentenceCharCount As Long
        Dim I As Long
        Dim Ending As String
    
        With TextRange
            Do
                .MoveEnd tomSentence, 1
                SentenceEnd = .End
                SentenceCharCount = SentenceEnd - .Start
                .Collapse tomStart
                For I = 0 To UBound(KeyWords)
                    If .FindText(KeyWords(I), SentenceCharCount, 0) > 0 Then Exit For
                Next
                If I <= UBound(KeyWords) Then
                    RichTextBox1.Locked = False
                    .Font.BackColor = vbYellow
                    RichTextBox1.Locked = True
                    .Collapse tomEnd
                    Do
                        .MoveStart tomWord, 1
                        .MoveEndUntil C1_SPACE Or C1_PUNCT, tomForward
                        If .End >= SentenceEnd Then
                            Exit Do
                        Else
                            If .End - .Start >= 3 Then
                                Ending = LCase$(Right$(.Text, 2))
                                For I = 0 To UBound(TwoLetterEndings)
                                    If TwoLetterEndings(I) = Ending Then Exit For
                                Next
                                If I <= UBound(TwoLetterEndings) Then
                                    RichTextBox1.Locked = False
                                    .Font.BackColor = vbCyan
                                    RichTextBox1.Locked = True
                                    Exit Do
                                End If
                            End If
                        End If
                    Loop
                    .MoveStart tomSentence, 1
                    If .Char = 13 Then
                        cmdNext.Enabled = False
                    End If
                    Exit Do 'Quit, since we found it.
                Else
                    .MoveStart tomSentence, 1
                    If .Char = 13 Then
                        cmdNext.Enabled = False
                        Exit Do 'Quit, since no more sentences.
                    End If
                End If
            Loop
        End With
    End Sub
    
    Private Sub Form_Load()
        Dim F As Integer
        Dim IUnknown As IUnknown
        
        With RichTextBox1
            F = FreeFile(0)
            Open "Text.txt" For Input As #F
                .Text = Input$(LOF(F), #F)
            Close #F
            SendMessage .hWnd, EM_GETOLEINTERFACE, 0, VarPtr(IUnknown)
            Set TextDocument = IUnknown
        End With
        Set TextRange = TextDocument.Range(0, 0)
        KeyWords = Split("was|has been|have been", "|")
        TwoLetterEndings = Split("ed|de|en", "|")
    End Sub
    
    Private Sub Form_Resize()
        If WindowState <> vbMinimized Then
            RichTextBox1.Move 0, 0, ScaleWidth
        End If
    End Sub
    Name:  sshotted.png
Views: 102
Size:  4.0 KB

    Of course RichEdit's typographic and punctuation rules probably follow the region and language settings of your Windows session.
    Attached Files Attached Files

  12. #12
    PowerPoster
    Join Date
    Jun 2001
    Location
    Trafalgar, IN
    Posts
    4,132

    Re: Textbox scan of word and the word following that word

    Quote Originally Posted by DataMiser View Post
    Here is a fairly basic and simple example showing how the Split() function can be used.
    Reading through the posts, I was wondering why InStr was the choice over splitting the string.

  13. #13

    Thread Starter
    Addicted Member
    Join Date
    Oct 2006
    Posts
    167

    Re: Textbox scan of word and the word following that word

    Thank you for the feedback! I will play around with the code suggested and see if I can make it work. It looks like I need to do the following:

    1) Identify key words "was, has been, is, will be" etc..
    2) Find the word that comes after the space after that key word.
    3) figure out how to get to the next space after that word.
    4) go back 3 spaces to check the ending of the 2nd word for "-ed, -en" etc

    5) write a routine that combines the two conditions and if both are true, add a warning to my listbox.
    6) continue scanning the textbox for more matches.

    I will play around with this and see if "something can be cobbled together" by me :-)

  14. #14
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,929

    Re: Textbox scan of word and the word following that word

    Code:
    TheString = "An apple was eaten by Newton"
    strWords = Split(TheString, " ")
    Just to be clear Split() takes care of steps 2 and 3 but there would be an exception that would need to be handled in the case of two word keys. Simple enough but different than single words.

    The code above will result in an array with 6 elements holding the following values
    strWords(0)="An"
    strWords(1)="apple"
    strWords(2)="was"
    strWords(3)="eaten"
    strWords(4)="by"
    strWords(5)="Newton"

    Split() will drop out the split character in this case space and parse the words into the array as shown.
    Of course there are still other things that you would have to deal with such as commas, periods and such but it can be a useful tool as can Instr() and Mid$() you just have to use them under the right conditions.

  15. #15

    Thread Starter
    Addicted Member
    Join Date
    Oct 2006
    Posts
    167

    Re: Textbox scan of word and the word following that word

    Hello,
    Thank you for all the suggestions.
    I was able to get Datamiser's sample to work for my purposes, adding matches in listboxes. However (and I'm quite sure this has a simple solution), I am trying to get TheString to take into account the full text2.text, not just the manually entered "An apple was eaten by Newton"


    Quote Originally Posted by DataMiser View Post
    Here is a fairly basic and simple example showing how the Split() function can be used.
    Code:
    Option Explicit
    Dim TheString As String
    Private Sub Form_Load()
    TheString = "An apple was eaten by Newton"
    End Sub

    I tried the following:

    Code:
    Option Explicit
    Dim TheString As String
    
    Private Sub Form_Load()
    TheString = text2.text
    End Sub
    
    
    
    
    End Sub
    But there was no response. (no error message, no text appeared to be scanned. I saw in another post on VBForums where someone had written similar code for a find function


    Code:
    Dim filename As String
    Dim thestring As String
    Dim Fnum As Long, Buffer As String, LineNo As Long
      Fnum = FreeFile ' Get next unused file number.
      filename = ("C:\...\word.txt")
      thestring = TxtSearch.Text
    So I tried imitating that with no joy.

    I know, this is a dumb question, but I am stumped.

    Thanks again for any ideas or solutions.

  16. #16
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,929

    Re: Textbox scan of word and the word following that word

    There is really nothing to that code you have. Allit does is assign theString a value. It does not do anything at all with it. Look at the examples posted.

  17. #17

    Thread Starter
    Addicted Member
    Join Date
    Oct 2006
    Posts
    167

    Re: Textbox scan of word and the word following that word

    Quote Originally Posted by DataMiser View Post
    There is really nothing to that code you have. Allit does is assign theString a value. It does not do anything at all with it. Look at the examples posted.


    OK, will go RTFC and see if I can figure it out. It's obviously something simple.
    Last edited by starscrea2; Dec 30th, 2018 at 03:37 PM.

  18. #18
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,929

    Re: Textbox scan of word and the word following that word

    Quote Originally Posted by starscrea2 View Post
    OK, will go RTFC and see if I can figure it out. It's obviously something simple.
    If you look at that example I posted there are two parts.

    1: The part in the form load that just gives our string a value which you reproduced.
    2: The part that looks at that string and does something with it.

    The 2nd part is missing from your posted code and without that it does nothing once the value is assigned and since you are not doing anything to display that value you won't see it either.

  19. #19

    Thread Starter
    Addicted Member
    Join Date
    Oct 2006
    Posts
    167

    Re: Textbox scan of word and the word following that word

    I got it to focus on the textbox text.

    Code:
    Private Sub Command1_Click()
    Dim strWords() As String
    strWords = Split(Text2.Text, " ")
    Dim x As Integer
    
    For x = 0 To UBound(strWords)
        If strWords(x) = "was" Then
       
       
           Text1.Text = "was found as word number " & x + 1 & " in the search string"
          
            
            If x < UBound(strWords) Then
                Text3.Text = "Next Word is " & strWords(x + 1)
               
              If Right$(strWords(x + 1), 2) = "en" Then
              List1.AddItem "Word ends in en"
              End If
             
    If Right$(strWords(x + 1), 2) = "ed" Then
              List1.AddItem "Word ends in ed"
              End If
    For some reason, it alerts me to the last word in the text string as being the next word, for example:

    "An apple was eaten, and a pie was exploded"


    It says "next word is exploded" instead of having 2 entries in the listbox, ie

    word ends in en (eaten)
    word ends in ed (exploded)

    I will play around with the code some more. The solution is probably similar to the code for a "find, find next" routine.

    Happy new year everyone, and thank you for your help!

  20. #20
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    803

    Re: Textbox scan of word and the word following that word

    As I pointed out in my response several days ago, if all you are doing is grabbing what is between spaces (which is exactly what you are doing with the split command), then you need to also do something to remove/account for the punctuation characters.

    In this case, what you assume to be the string "eaten" is almost certainly actually "eaten,", and your "check if the last two characters are en" logic is failing because of that.

  21. #21

    Thread Starter
    Addicted Member
    Join Date
    Oct 2006
    Posts
    167

    Re: Textbox scan of word and the word following that word

    Quote Originally Posted by OptionBase1 View Post
    As I pointed out in my response several days ago, if all you are doing is grabbing what is between spaces (which is exactly what you are doing with the split command), then you need to also do something to remove/account for the punctuation characters.

    In this case, what you assume to be the string "eaten" is almost certainly actually "eaten,", and your "check if the last two characters are en" logic is failing because of that.
    I tried taking the punctuation marks out of the string before scanning, and the result is the same.




    Code:
    Dim mystring1 As String
    mystring1 = Replace(Text2.Text, ",", "", 1, , vbTextCompare)
         Text2.Text = mystring1
    
    
    Dim mystring2 As String
    mystring2 = Replace(Text2.Text, ":", "", 1, , vbTextCompare)
         Text2.Text = mystring2
    
    Dim mystring3 As String
    mystring3 = Replace(Text2.Text, "!", "", 1, , vbTextCompare)
         Text2.Text = mystring3
    
    
    Dim mystring4 As String
    mystring4 = Replace(Text2.Text, ";", "", 1, , vbTextCompare)
         Text2.Text = mystring4
    
    Dim mystring5 As String
    mystring5 = Replace(Text2.Text, "]", "", 1, , vbTextCompare)
         Text2.Text = mystring5
         
       Dim mystring6 As String
    mystring6 = Replace(Text2.Text, ")", "", 1, , vbTextCompare)
         Text2.Text = mystring6
         
         Dim mystring7 As String
    mystring7 = Replace(Text2.Text, ".", "", 1, , vbTextCompare)
         Text2.Text = mystring7
    
    Dim mystring8 As String
    mystring8 = Replace(Text2.Text, "?", "", 1, , vbTextCompare)
         Text2.Text = mystring8
         
         Dim mystring9 As String
    mystring9 = Replace(Text2.Text, "-", "", 1, , vbTextCompare)
         Text2.Text = mystring9
         
         Dim mystring10 As String
    mystring10 = Replace(Text2.Text, " - ", "", 1, , vbTextCompare)
         Text2.Text = mystring10
    The code above strips all punctuation from the textbox.

    Here is the result after scanning the following string:

    "An apple was eaten, and a pie was exploded"

    The 1st list box says "was" found as word 8 in the search string

    The 2nd list box says "Next word is exploded"

    So it is still skipping word number 3, "was".

    anyway, I'll keep playing with it. Thanks!
    Last edited by starscrea2; Jan 1st, 2019 at 10:09 AM.

  22. #22
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    2,062

    Re: Textbox scan of word and the word following that word

    Hi,

    quit supprised you are still working on this with all the Tips and Post's in this thread.

    well to round up all the ways you can work this out, here the use of Regex
    you will have to add 3 command buttons and 3 Listboxes.

    here the textfile I created for testing call Newton.txt

    Code:
    The apple was eaten. The apple was eat quickly.
    test test
    I noticed the apple was eate, so I screamed.
    An apple was eaten, and a pie was exploded
    here the Form code
    Code:
    Option Explicit
    Private pRegEx As Object
    
    Public Property Get oRegEx() As Object
       If (pRegEx Is Nothing) Then
          Set pRegEx = CreateObject("Vbscript.Regexp")
       End If
       Set oRegEx = pRegEx
    End Property
    
    Public Function ReadFile(ByRef Path As String) As String
       Dim FileNr As Long
       On Error Resume Next
       If FileLen(Path) = 0 Then Exit Function
       On Error GoTo 0
       FileNr = FreeFile
       Open Path For Binary As #FileNr
       ReadFile = Space$(LOF(FileNr))
       Get #FileNr, , ReadFile
       Close #FileNr
    End Function
    
    Private Sub Command1_Click()
     Dim cMatches As Object
       Dim m As Object
       With oRegEx
        .Pattern = "(\w\w+)" 'add each word to Listbox
        .Global = True
        .MultiLine = True
          
        Set cMatches = .Execute(ReadFile("E:\Newton.txt"))
          For Each m In cMatches
           List1.AddItem m.SubMatches(0)
          Next
            List1.AddItem "---------------------------"
            List1.AddItem " the count is :" & cMatches.Count 'print the Wordcount
       End With
       Set m = Nothing
       Set cMatches = Nothing
    End Sub
    
    Private Sub Command2_Click()
     Dim cMatches As Object
       Dim m As Object
       With oRegEx
        .Pattern = "(was|apple)" 'search word(s) was and apple in Textfile
        .Global = True
        .MultiLine = True
        Set cMatches = .Execute(ReadFile("E:\Newton.txt"))
          For Each m In cMatches
           List2.AddItem m.SubMatches(0)
          Next
            List2.AddItem "---------------------------"
            List2.AddItem " the count is :" & cMatches.Count 'print the Wordcount
       End With
       Set m = Nothing
       Set cMatches = Nothing
    End Sub
    
    Private Sub Command3_Click()
     Dim cMatches As Object
       Dim m As Object
       With oRegEx
        .Pattern = "was\s(\w+)" 'find was and then the next word
        .Global = True
        .MultiLine = True
        Set cMatches = .Execute(ReadFile("E:\Newton.txt"))
          For Each m In cMatches
          List3.AddItem m.Value & " ; " & m.FirstIndex & " ; " & m.Length
       Next
       End With
       Set m = Nothing
       Set cMatches = Nothing
    
    
    End Sub
    Happy new Year and
    good luck
    Last edited by ChrisE; Jan 1st, 2019 at 10:52 AM. Reason: cleaned code up
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  23. #23
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,929

    Re: Textbox scan of word and the word following that word

    For some reason, it alerts me to the last word in the text string as being the next word, for example:

    "An apple was eaten, and a pie was exploded"
    The reason you see only the last match in the text box is because your code is written to do exactly that. When it sees the first match it would put it in the text box but then when it sees another it replaces what is in the text box with the new value.

    As for the listbox it looks like there should be two entries there unless of course there is some other character there that is causing your Right$() to fail on one of them.

    On another note you do not need to create a bunch of vars to do some simple replacement on your string. You can use the same var over and over again.

    The below will give you the same results, less typing, faster and easier to read.
    Code:
    Text2.Text = Replace(Text2.Text, ";", "", 1, , vbTextCompare)
    Text2.Text = Replace(Text2.Text, "]", "", 1, , vbTextCompare)

  24. #24
    PowerPoster
    Join Date
    Feb 2006
    Posts
    20,561

    Re: Textbox scan of word and the word following that word

    While handy to have, and speed often isn't a significant factor...

    Replace, Split, Join were late additions to VB and based on code written as part of VBScript originally. These are not the sharpest knives in the drawer, especially if you force Replace to scan taking the slow-boat by specifying vbTextCompare when it adds no value.

  25. #25

    Thread Starter
    Addicted Member
    Join Date
    Oct 2006
    Posts
    167

    Re: Textbox scan of word and the word following that word

    Quote Originally Posted by ChrisE View Post

    Hi,

    quit surprised you are still working on this with all the Tips and Post's in this thread.

    I am surprised, too. I can make some pretty nice tools manipulating databases and using SQL queries etc, but something that should be simple appears to be completely beyond me. It's obviously one line I am missing, one "+1" somewhere or something like that, but I can't figure it out. Oh well.

    Thanks anyway.

  26. #26
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    2,062

    Re: Textbox scan of word and the word following that word

    Quote Originally Posted by starscrea2 View Post
    I am surprised, too. I can make some pretty nice tools manipulating databases and using SQL queries etc, but something that should be simple appears to be completely beyond me. It's obviously one line I am missing, one "+1" somewhere or something like that, but I can't figure it out. Oh well.

    Thanks anyway.
    Hi,

    see my sample with Regex

    Code:
    Private Sub Command3_Click()
     Dim cMatches As Object
       Dim m As Object
       With oRegEx
        .Pattern = "was\s(\w+)" 'find was and then the next word
        .Global = True
        .MultiLine = True
        Set cMatches = .Execute(ReadFile("E:\Newton.txt"))
          For Each m In cMatches
          List3.AddItem m.Value & " ; " & m.FirstIndex & " ; " & m.Length
       Next
       End With
       Set m = Nothing
       Set cMatches = Nothing
    
    End Sub
    will return was and then the next word

    output with Debug.Print
    Code:
    was eaten ; 10 ; 9
    was eat ; 31 ; 7
    was eate ; 80 ; 8
    was eaten ; 115 ; 9
    was exploded ; 136 ; 12
    HTH
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  27. #27
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,929

    Re: Textbox scan of word and the word following that word

    Quote Originally Posted by dilettante View Post
    While handy to have, and speed often isn't a significant factor...

    Replace, Split, Join were late additions to VB and based on code written as part of VBScript originally. These are not the sharpest knives in the drawer, especially if you force Replace to scan taking the slow-boat by specifying vbTextCompare when it adds no value.
    Agreed, I was just pasting what he had and changing the var assignment. I started to remove the optional parameters on the replace statements but then decided to leave them in the example.

    It's funny I had been using VB6 for a long time before I saw the Split() had been added. I had previously written my own functions for split and replace in VB5 and had them in a common module that I used in most of my programs. Maybe I should revisit those and see how they compare in speed just for kicks.

  28. #28
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,929

    Re: Textbox scan of word and the word following that word

    Quote Originally Posted by starscrea2 View Post
    I am surprised, too. I can make some pretty nice tools manipulating databases and using SQL queries etc, but something that should be simple appears to be completely beyond me. It's obviously one line I am missing, one "+1" somewhere or something like that, but I can't figure it out. Oh well.

    Thanks anyway.
    Like I said your code is putting both values into the text boxes, the problem is that the second match overwrites the first one and it happens very very fast so you never see the first one.
    If you had used debug.print as I showed in my example you would have saw that it did in fact work.

  29. #29
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    2,062

    Re: Textbox scan of word and the word following that word

    changed a bit
    Code:
    Private Sub Command3_Click()
     Dim cMatches As Object
       Dim m As Object
       With oRegEx
        .Pattern = "was\s(\w+)" 'find was and then the next word
        .Global = True
        .MultiLine = True
        Set cMatches = .Execute(ReadFile("E:\Newton.txt"))
          For Each m In cMatches
          List3.AddItem m.Value & " ; " & m.FirstIndex & " ; " & m.Length
          List3.AddItem Right(m.Value, 2)
          List3.AddItem "--------------"
      Debug.Print m.Value & " ; " & m.FirstIndex & " ; " & m.Length
         Debug.Print Right(m.Value, 2)
         Debug.Print "--------------"
          
       Next
       End With
       Set m = Nothing
       Set cMatches = Nothing
    End Sub
    output
    Code:
    was eaten ; 10 ; 9
    en
    --------------
    was eat ; 31 ; 7
    at
    --------------
    was eate ; 80 ; 8
    te
    --------------
    was eaten ; 115 ; 9
    en
    --------------
    was exploded ; 136 ; 12
    ed
    --------------
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  30. #30

    Thread Starter
    Addicted Member
    Join Date
    Oct 2006
    Posts
    167

    Re: Textbox scan of word and the word following that word

    Hello,
    I got the program to do pretty much what I wanted it to do.


    I just wanted to pop in and say thank you again for the help, and sorry I was so slow in replying, (and so slow in grasping the concept, apparently).


    Here is some of the code if anyone ever needs this exact requirement in the future. Comments are mine, code is from the generous ppl at VBForums.

    Code:
    Private Sub Command1_Click()
    Dim strWords() As String
    strWords = Split(Text2.Text, " ")
    Dim x As Integer
    
    For x = 0 To UBound(strWords) - 1
        
        
           
        'looking for phrase 'has been' - break into 'has', then look for 'been'
        If strWords(x) = "has" Then
            
    
            
                'look at the next word, and the last 4 letters of the word
                Select Case Right$(strWords(x + 1), 4)
                    'is the word following 'has'  the word 'been'?
                    Case "been"
                        List1.AddItem "phrase 'has been' was found"
                  
                   
                End Select
                
                   
              
    
        'looking for word was
        If strWords(x) = "was" Then
            
    
                
                Select Case Right$(strWords(x + 1), 2)
                    'is the word following was ending in en?
                    Case "en"
                        List1.AddItem "Word following 'was' ends in en"
                   'is the word following was ending in ed?
                    Case "ed"
                        List1.AddItem "Word following 'was' ends in ed"
                    'is the word following was ending in es?
                    Case "es"
                        List1.AddItem "Word following 'was' ends in es"
                   
                End Select
            
          End if
           End if
            End if
    Next
    End Sub
    Last edited by starscrea2; Jan 20th, 2019 at 11:23 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width