該方法在標(biāo)準(zhǔn)模塊或類模塊中查找指定的文本。
expression.Find(Target, StartLine, StartColumn, EndLine, EndColumn, WholeWord, MatchCase, PatternSearch)
expression 必需。返回“應(yīng)用于”列表中的一個對象的表達(dá)式。
Target 必需 String 型。字符串表達(dá)式,其值為要查找的文本。
StartLine 必需 Long 型。該值指定開始搜索的行。如果找到相匹配的文本,StartLine 參數(shù)值設(shè)為找到的匹配文本的開始字符所在的行號。
StartColumn 必需 Long 型。該值指定開始搜索的列。行中的每一字符都在不同的列中,模塊左邊開始的列數(shù)為零。如果找到相匹配的文本,StartColumn 參數(shù)值將設(shè)為找到的匹配文本的開始字符所在的列號。
EndLine 必需 Long 型。該值指定停止搜索的行。如果找到相匹配的文本,EndLine 參數(shù)值將設(shè)為找到的匹配文本的結(jié)束字符所在的行號。
EndColumn 必需 Long 型。該值指定停止搜索的列。如果找到匹配的文本,EndColumn 參數(shù)值將設(shè)為找到的匹配文本的開始字符所在的列號。
WholeWord 可選 Boolean 型。True 值將搜索匹配整個詞的文本。默認(rèn)值為 False。
MatchCase 可選 Boolean 型。True 值將搜索大小寫與 Target 參數(shù)匹配的詞。默認(rèn)值為 False。
PatternSearch 可選 Boolean 型。True 值搜索 Target 參數(shù)包含通配符如星號 (*) 或問號 (?) 的文本。默認(rèn)值為 False。
Find 方法可在 Module 對象中搜索指定的文本字符串。如果找到字符串,Find 方法返回 True。
要確定找到的搜索文本在模塊中的位置,請將 Find 方法的 StartLine、StartColumn、EndLine 和 EndColumn 參數(shù)設(shè)為空。如果找到匹配的文本,這些參數(shù)將包含該搜索文本開始 (StartLine、StartColumn) 和結(jié)束 (EndLine、 EndColumn) 的行編號和列的位置。
例如,如果搜索文本在第 5 行中找到,從第 10 列開始,到 20 列結(jié)束,那么這些參數(shù)值將是: StartLine = 5、StartColumn = 10、EndLine = 5、EndColumn = 20。
下面的函數(shù)在模塊中查找指定的字符串,并以指定的新行替換包含該字符串的行:
Function FindAndReplace(strModuleName As String, _
strSearchText As String, _
strNewText As String) As Boolean
Dim mdl As Module
Dim lngSLine As Long, lngSCol As Long
Dim lngELine As Long, lngECol As Long
Dim strLine As String, strNewLine As String
Dim intChr As Integer, intBefore As Integer, _
intAfter As Integer
Dim strLeft As String, strRight As String
' Open module.
DoCmd.OpenModule strModuleName
' Return reference to Module object.
Set mdl = Modules(strModuleName)
' Search for string.
If mdl.Find(strSearchText, lngSLine, lngSCol, lngELine, _
lngECol) Then
' Store text of line containing string.
strLine = mdl.Lines(lngSLine, Abs(lngELine - lngSLine) + 1)
' Determine length of line.
intChr = Len(strLine)
' Determine number of characters preceding search text.
intBefore = lngSCol - 1
' Determine number of characters following search text.
intAfter = intChr - CInt(lngECol - 1)
' Store characters to left of search text.
strLeft = Left$(strLine, intBefore)
' Store characters to right of search text.
strRight = Right$(strLine, intAfter)
' Construct string with replacement text.
strNewLine = strLeft & strNewText & strRight
' Replace original line.
mdl.ReplaceLine lngSLine, strNewLine
FindAndReplace = True
Else
MsgBox "Text not found."
FindAndReplace = False
End If
Exit_FindAndReplace:
Exit Function
Error_FindAndReplace:
MsgBox Err & ": " & Err.Description
FindAndReplace = False
Resume Exit_FindAndReplace
End Function