|
本帖最后由 413191246se 于 2015-8-18 13:38 编辑
* 原因:Word2003本身的《文件搜索》功能不能查找到文件!WIN7系统也无法找到关键词文件,网络上搜索软件试用好几个也无法查找到文件,偶然看到一个网页谈到 .TextOrProperty属性可以查找正文关键词来返回文件,验证OK!看来只能靠 VBA 了!(其实以前也知道这条语句,但没重视。)
* 功能:在指定文件夹中,通过按《文件名关键词》/《正文关键词》/《文件名关键词 + 正文关键词》三个模式搜索 Word 文档(*.doc)。
* 当找到的文件数少于 22 个时,自动打开所有找到的文件(大家可以自行修改这个值);否则,询问是否打开。自动提取文件名到空白文档中。
* 注意事项:在运行此宏期间,请耐心等待,不要做各种键盘和鼠标运行,以免程序中途停止。如果不想等待,可以按 Ctrl + PauseBreak 中止程序。
*《循环遍历文件夹_文件搜索》宏(实用版)v1代码:
- Sub 循环遍历文件夹_文件搜索()
- On Error Resume Next
- Dim fd As FileDialog, i As Long, doc As Document, p As String, j As String, k As Long, q As String, r As String, s As String, t As String, a As String
- Set fd = Application.FileDialog(msoFileDialogFolderPicker)
- If fd.Show = -1 Then p = fd.SelectedItems(1) Else Exit Sub
- Set fd = Nothing
- If MsgBox("是否搜索文件夹 " & p & " ?", vbYesNo + vbExclamation, "循环遍历文件夹_文件搜索") = vbNo Then Exit Sub
- j = MsgBox("是:<文件名关键词> 否:<正文关键词> 取消:<文件名关键词+正文关键词>", vbYesNoCancel + vbExclamation, "请选择文件搜索模式!")
- If j = vbYes Then
- k = 1: q = "<文件名关键词>": r = "任职"
- ElseIf j = vbNo Then
- k = 2: q = "<正文关键词>": r = "秦楚楚"
- Else
- k = 3: q = "<文件名关键词+正文关键词>": r = "任职,秦楚楚"
- End If
- reipt:
- a = InputBox("如果同时输入<文件名关键词>+<正文关键词>,必须以中文逗号分隔!如:“任职,秦楚楚”", "请输入" & q & "搜索文件!", r)
- If a = "" Then Exit Sub
- If k = 1 Then
- If a Like "*,*" Then GoTo reipt
- s = a
- ElseIf k = 2 Then
- If a Like "*,*" Then GoTo reipt
- t = a
- ElseIf k = 3 Then
- If Not (a Like "*,*") Then GoTo reipt
- s = Left(a, InStr(a, ",") - 1): t = Mid(a, InStr(a, ",") + 1)
- End If
- Set doc = Documents.Add
- With Application.FileSearch
- .NewSearch
- .LookIn = p
- .SearchSubFolders = True
- If k = 1 Then
- .FileName = "*" & s & "*.doc"
- ElseIf k = 2 Then
- .FileName = "*.doc"
- .TextOrProperty = t
- ElseIf k = 3 Then
- .FileName = "*" & s & "*.doc"
- .TextOrProperty = t
- End If
- If .Execute > 0 Then
- For i = 1 To .FoundFiles.Count
- doc.Content.InsertAfter Text:=.FoundFiles(i) & vbCr
- Next i
- If .FoundFiles.Count >= 22 Then If MsgBox("搜索完毕!共发现 " & .FoundFiles.Count & " 个文件!——是否打开搜索的文件?", vbYesNo + vbExclamation, "循环遍历文件夹_文件搜索") = vbNo Then End
- For i = 1 To .FoundFiles.Count
- Documents.Open FileName:=.FoundFiles(i)
- Next i
- MsgBox "搜索完毕!共发现 " & .FoundFiles.Count & " 个文件!", vbOKOnly + vbExclamation, "循环遍历文件夹_文件搜索"
- Else
- MsgBox "未发现文件!", vbOKOnly + vbCritical, "循环遍历文件夹_文件搜索"
- End If
- End With
- End Sub
复制代码 |
|