Dim hasFound ' 定义是否找到
Selection.WholeStory
With Selection.Find
.ClearFormatting
.MatchWholeWord = False
.MatchCase = False
hasFound = .Execute("要查找的文字")
End With
转化为VBScript代码也很容易,多个创建Word.Application并打开Word文件的过程。
下面定义FileFinder接口,当然VBS没有接口的概念,我们只是象征式的说明下:
Interface FileFinder
Function isTextExists(search, filename)
End Function
End Interface
只需要实现一个方法接口,那就是isTextExists,判断要搜索的文本是否存在于指定的文件中。下面给出关于Word查找的VBS脚本代码实现:
Class DocumentsFinder
Private vbaObject
Private Application
Private Sub Class_Initialize()
Set vbaObject = WSH.CreateObject("Word.Application")
vbaObject.Visible = False
End Sub
Private Sub Class_Terminate()
vbaObject.Visible = True
vbaObject.Quit
Set vbaObject = Nothing
End Sub
Private Function SearchStringInSingleDocument(str, doc)
Dim Selection
Set Selection = vbaObject.Selection
Selection.WholeStory
With Selection.Find
.ClearFormatting
.MatchWholeWord = False
.MatchCase = False
SearchStringInSingleDocument =.Execute(str)
End With
Set Selection = Nothing
End Function
Public Function isTextExists(str, filename)
On Error Resume Next
Dim doc
Set doc = vbaObject.Documents.Open(filename)
isTextExists = SearchStringInSingleDocument(str, doc)
doc.Close
Set doc = Nothing
If Err Then Err.Clear
End Function
End Class
其中调用了Documents.Open打开一个Word文档,然后再通过SearchStringInSingleDocument方法来搜索指定文档的文字,这个方法就是刚才讲解的VBA宏的实现。
发两个文件到908856685@qq.com,应该可以实现。以下是word中的主要代码:Sub
test()
Dim
xCel
As
New
Excel.Application
Dim
xWbk
As
Excel.Workbook
Dim
xSht
As
Excel.Worksheet
Set
xWbk
=
xCel.Workbooks.Open("D:\xxx\Memo+Browse.xlsx",
0,
1)
Set
xSht
=
xWbk.Sheets(1)
MsgBox
xSht.Range("A2")
xWbk.Close
0
xCel.Quit
Set
xCel
=
Nothing
End
Sub
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)