Sunday, June 17, 2012

Implementasi Pencarian Pada RichTextBox Control

Option Explicit

Private Sub Command1_Click()
HighlightWords RichTextBox1, "text", vbRed
End Sub

Private Function HighlightWords(rtb As RichTextBox, sFindString As String, lColor As Long) As Integer

Dim lFoundPos As Long
Dim lFindLength As Long
Dim lOriginalSelStart As Long
Dim lOriginalSelLength As Long
Dim iMatchCount As Integer

lOriginalSelStart = rtb.SelStart
lOriginalSelLength = rtb.SelLength

lFindLength = Len(sFindString)

lFoundPos = rtb.Find(sFindString, 0, , rtfNoHighlight)
While lFoundPos > 0
iMatchCount = iMatchCount + 1

rtb.SelStart = lFoundPos
rtb.SelLength = lFindLength
rtb.SelColor = lColor

lFoundPos = rtb.Find(sFindString, lFoundPos + lFindLength, , rtfNoHighlight)
Wend

rtb.SelStart = lOriginalSelStart
rtb.SelLength = lOriginalSelLength

HighlightWords = iMatchCount

End Function