VB应用程序中实现查找和替换功能
' Search from the begining of the document.
Cnt = 1
' This is endless loop (terminated on a condition checked inside
' the loop body).
While (1)
FndPos = InStr(Cnt, SourceText, txtSearchTerm.Text, CaseSense)
' When a match is found, replace it appropriately.
If (FndPos > 0) Then
SourceText = ReplaceFun(SourceText, FndPos, Len(txtSearchTerm.Text), txtReplaceWithString.Text)
Cnt = FndPos + SearchTermLen
Else
Cnt = Cnt + 1
End If
' Whether a replacement was done at all or not
If (Cnt >= Len(SourceText)) Then
txtClient.Text = SourceText
If (SourceTextCopy <> SourceText) Then
MsgBox "Finished replacing all occurrences.", vbInformation + vbOKOnly, "Replaced All"
Else
MsgBox "No matching strings found. No text replaced.", vbInformation + vbOKOnly, "No Replacement"
End If
Unload Me
Exit Sub
End If
' Else Restart from henceforth
Wend
Exit Sub
ErrHandler:
Response = MsgBox("An error ocurred while searching. Inform the developer with details.", _
vbExclamation + vbOKOnly, "Error Searching")
End Sub
Private Sub Form_Load()
' Default SearchTerm must be the one selected by the user in
' MainForm
If Len(txtClient.SelText) <> 0 Then
txtSearchTerm.Text = txtClient.SelText
End If
End Sub
Function ReplaceFun(Source As String, FromPos As Integer, _
Length As Integer, StringTBReplaced _
As String) As String
' Replaces a source string with new one appropriately
Dim ResultStr As String
ResultStr = Left(Source, FromPos - 1)
ResultStr = ResultStr & StringTBReplaced
ResultStr = ResultStr & Right(Source, Len(Source) - FromPos - Length + 1)
ReplaceFun = ResultStr
End Function
Private Sub txtReplaceWithString_Change()
Call EnableDisableReplaceButton
End Sub
Private Sub txtReplaceWithString_GotFocus()
' Select the contents of the textbox
If Len(txtReplaceWithString.Text) <> 0 Then
txtReplaceWithString.SelStart = 0
txtReplaceWithString.SelLength = Len(txtReplaceWithString.Text)
End If
End Sub
Private Sub txtSearchTerm_Change()
Call EnableDisableReplaceButton
End Sub
Private Sub EnableDisableReplaceButton()
If Len(txtSearchTerm.Text) <> 0 _
And Len(txtReplaceWithString.Text) <> 0 Then
cmdReplace.Enabled = True
Else
cmdReplace.Enabled = False
End If
End Sub
Private Sub txtSearchTerm_GotFocus()
' Select the contents of textbox
If Len(txtSearchTerm.Text) <> 0 Then
txtSearchTerm.SelStart = 0
txtSearchTerm.SelLength = Len(txtSearchTerm.Text)
End If
End Sub
四、代码说明
公用接口SearchnReplace的"查找替换"算法带有普遍性,使用这种方法,"查找替换"功能可以在任何应用程序中实现,而不用更改frmFindReplace的代码。只是在调用公用接口的地方需要做一些小的改动。
"查找和替换"代码在cmdReplace_Click()过程与ReplaceFun() 函数下,让我们从cmdReplace_Click()过程开始。
首先,变量CaseSense用于跟踪用户的选择,是否是大小写敏感,如果用户选择大小写敏感的话,它的值设置为0,否则,设置为1。变量SourceText和SourceTextCopy用于保存frmMainForm窗体中 txtClientArea的内容(或者是用户在主窗体中为TextBox提供的内容,对于本程序来说,它就是txtClientArea),两个变量保存同样的内容将在下面进行解释(一个是临时变量)。变量Cnt用来跟踪文档的结束,当重新从文档开始处进行"查找替换"时它将非常有用。这个变量含蓄地说明了当前光标的位置,下次的"查找替换"将从这个位置开始。
VB论坛
Tags:
作者:佚名评论内容只代表网友观点,与本站立场无关!
评论摘要(共 0 条,得分 0 分,平均 0 分)
查看完整评论