|
楼主 |
发表于 2024-3-21 13:50
|
显示全部楼层
换个思路,需求已实现,分享给大家。唯一不足就是路径中不能有中文...
Sub ExtractParagraphsWithKeyword()
Dim fso As Object
Dim folder As Object
Dim file As Object
Dim docApp As Word.Application
Dim doc As Word.Document
Dim para As Word.Paragraph
Dim keyword As String
Dim ws As Worksheet
Dim i As Integer
Dim j As Integer
Dim filename As String
Dim foundParagraphs As Integer
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("C:\Documents\") ' 修改为包含文档的文件夹路径特别注意路径不能有中文
Set ws = ThisWorkbook.Sheets("Sheet1") ' 修改为输出结果的工作表名称
Set docApp = New Word.Application
docApp.Visible = False
keyword = "关键字" ' 修改为需要搜索的关键字
i = 1 ' 输出到Excel的起始行
foundParagraphs = 0
For Each file In folder.Files
If LCase(fso.GetExtensionName(file.Name)) = "doc" Or LCase(fso.GetExtensionName(file.Name)) = "docx" Then
Set doc = docApp.Documents.Open(file.Path)
filename = file.Name ' 文件名
For Each para In doc.Paragraphs
If InStr(1, para.Range.Text, keyword, vbTextCompare) > 0 Then
ws.Cells(i, 1).Value = filename ' 输出文件名
ws.Cells(i, 2).Value = para.Range.Text ' 输出段落文本
i = i + 1
foundParagraphs = foundParagraphs + 1
End If
Next para
doc.Close
End If
Next file
ws.Cells(1, 3).Value = "Found Paragraphs: " & foundParagraphs
docApp.Quit
Set docApp = Nothing
Set fso = Nothing
End Sub |
|