K. Smith
K. Smith

Reputation: 33

Identifying a word's and sentences

I need to produce code within Visual Basic that identify's a words position. For example, my sentence could write 'This is my Visual Basic Project'. If the user entered the word 'my', the output will open another form displaying 'Your word is in the 3rd position'. Its required to use strings then change it into an array.

My design for this project is fairly simple:

A TextBox for thee user to enter text.
A "Confirm" Button.
And an "Exit" Button.

Also, in the Form containing the output (when confirming that the button has been clicked) there is a Label (giving answer) and an "ok" Button to return you back to the main program. Finally, if their word is not within the sentence, an error message should appear. The program should be caps sensitive.

I am fairly new to programming and would love any help. I would appreciate it if you could return some code for the Buttons, TextBox's and a whole program.

Really please. Many thanks!!

Upvotes: 0

Views: 458

Answers (1)

S Meaden
S Meaden

Reputation: 8260

You haven't specified a platform, so this answer is only for Office Development scenarios.

The Microsoft Word Object Model is useful here. You can loop through a Sentence object, looping through its Words collection. Loop through the Words collection until you get a match. So some code to run in Microsoft Word

Sub SetUpSentence()

    Dim currentSelection As Word.Selection
    Set currentSelection = Application.Selection

    Application.Options.Overtype = False

    currentSelection.TypeText Text:="This is some text"
End Sub

Sub TestFindWord()
    Debug.Print FindWord("some")
End Sub

Function FindWord(ByVal sWord As String) As Long

    Dim oWords As Word.Words
    Set oWords = ActiveDocument.Words

    Dim lIndex As Long
    lIndex = 0
    Dim oRange As Word.Range
    For Each oRange In oWords
        lIndex = lIndex + 1
        If Trim(oRange.Text) = sWord Then
            FindWord = lIndex
            Exit Function
        End If
    Next oRange

End Function

Upvotes: 1

Related Questions