Visual Basic - Creating a find word in document
=====================================================================================
Question
i want to create a program which can find a specified word in a
rich text box of a visual basic form and can highlight the word and move the cursor to that word. plz help me with the coding
Answer
I've create a sample you can use to figure this one out. Basically you want to use the Instr function to find the text. You can use the SelStart and SelLength properties of the textbox to highlight the word and move the cursor once found.
I've created a new form and added a richtextbox named txtDocument. I've added a regular textbox named txtFind. Finally I've added a button named cmdFind. Here is the code to search for text. Each time you click the button it searches for the next match.
Option Explicit
Private Sub cmdFind_Click()
ExecuteSearch
End Sub
Private Sub ExecuteSearch()
Dim sFind As String
Dim nFindIndex As Integer
Dim nStartIndex As Integer
sFind = txtFind.Text
nStartIndex = txtDocument.SelStart + txtDocument.SelLength
If nStartIndex = 0 Then
nStartIndex = 1
ElseIf nStartIndex >= Len(txtDocument.Text) Then
If PromptForSearchFromBeginning Then
txtDocument.SelStart = 1
txtDocument.SelLength = 0
nStartIndex = 1
End If
End If
nFindIndex = InStr(nStartIndex, txtDocument.Text, txtFind.Text, vbBinaryCompare)
If nFindIndex > 0 Then
txtDocument.SelStart = nFindIndex - 1
txtDocument.SelLength = Len(txtFind.Text)
txtDocument.SetFocus
Else
If InStr(1, txtDocument.Text, txtFind.Text, vbBinaryCompare) Then
If PromptForSearchFromBeginning Then
txtDocument.SelStart = 1
txtDocument.SelLength = 0
'Make recursive call
ExecuteSearch
End If
End If
End If
End Sub
Private Function PromptForSearchFromBeginning() As Boolean
Dim eMsgBxRslt As VbMsgBoxResult
Dim bRetVal As Boolean
eMsgBxRslt = MsgBox("End of Document reached" & vbNewLine & "Would you like to start from the beginning?", vbYesNo, "End of Document")
bRetVal = (eMsgBxRslt = vbYes)
PromptForSearchFromBeginning = bRetVal
End Function
No comments:
Post a Comment