InStr函數提供了在一個字符串中查找另一個字符串的功能。我們可以把TextBox中的文本看作是一個字符串,這樣,查找就得以實現了。同時,InStr還允許設置查找的起始位置,繼續查找功能因而也不難解決。以下是詳細的代碼:
'首先,聲明窗體級變量:
Dim Search As String '聲明要查找的變量
'查找代碼:
Dim Where1 '獲取需要查找的字符串變量
Text1.SetFocus '文本框獲得焦點,以顯示所找到的內容Search = InputBox("請輸入要查找的字詞:")
Where1 = InStr(Text1.Text, Search) '在文本中查找字符串
If Where1 Then
'若找到則設置選定的起始位置并使找到的字符串高亮
Text1.SelStart = Where1 - 1
Text1.SelLength = Len(Search)
' Me.Caption = Where1 '測試用
'否則給出提示
Else: MsgBox "未找到所要查找的字符串。", vbInformation, "提示"
End If
'繼續查找 [注意:與“查找”有所不同]
dim Where2
Dim StartMe As Integer '查找的起始位置變量
Text1.SetFocus '文本框獲得焦點
StartMe = Text1.SelLength + Text1.SelStart + 1 '給變量賦值
where2 = InStr(StartMe, Text1.Text, Search) '令其從上次找到的地方找起
'以下和“查找”的一樣了
If where2 Then
Text1.SelStart = where2 - 1
Text1.SelLength = Len(Search)
Else: MsgBox "未找到所要查找的字符串。", vbInformation, "提示"
End If
文章來源于領測軟件測試網 http://www.kjueaiud.com/