Excel VBAmacros在.doc文件中查找文本

我想写一个macros,它可以在大约100个文件夹中find名称为XXXX_TestSummary的文件,并在这些文件中search单词“Failed”。 macros应该返回文本或Excel中包含单词失败的文件名。

我卡住,因为我只能find文件夹中的文件名。 下面是代码

Sub MainList() 'Updateby20150706 Set folder = Application.FileDialog(msoFileDialogFolderPicker) If folder.Show <> -1 Then Exit Sub xDir = folder.SelectedItems(1) Call ListFilesInFolder(xDir, True) End Sub Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean) Dim xFileSystemObject As Object Dim xFolder As Object Dim xSubFolder As Object Dim xFile As Object Dim rowIndex As Long Set xFileSystemObject = CreateObject("Scripting.FileSystemObject") Set xFolder = xFileSystemObject.GetFolder(xFolderName) rowIndex = Application.ActiveSheet.Range("A65536").End(xlUp).Row + 1 For Each xFile In xFolder.Files Application.ActiveSheet.Cells(rowIndex, 1).Formula = xFile.Name rowIndex = rowIndex + 1 Next xFile If xIsSubfolders Then For Each xSubFolder In xFolder.SubFolders ListFilesInFolder xSubFolder.path, True Next xSubFolder End If Set xFile = Nothing Set xFolder = Nothing Set xFileSystemObject = Nothing End Sub Function GetFileOwner(ByVal xPath As String, ByVal xName As String) Dim xFolder As Object Dim xFolderItem As Object Dim xShell As Object xName = StrConv(xName, vbUnicode) xPath = StrConv(xPath, vbUnicode) Set xShell = CreateObject("Shell.Application") Set xFolder = xShell.Namespace(StrConv(xPath, vbFromUnicode)) If Not xFolder Is Nothing Then Set xFolderItem = xFolder.ParseName(StrConv(xName, vbFromUnicode)) End If If Not xFolderItem Is Nothing Then GetFileOwner = xFolder.GetDetailsOf(xFolderItem, 8) Else GetFileOwner = "" End If Set xShell = Nothing Set xFolder = Nothing Set xFolderItem = Nothing End Function 

可以请任何人帮助解决这个问题?

如果你使用上面的代码,你需要在你的循环中添加一些代码:

 For Each xFile In xFolder.Files Application.ActiveSheet.Cells(rowIndex, 1).Formula = xFile.Name (ADD CODE HERE) rowIndex = rowIndex + 1 Next xFile 

或者,也可以向该循环的顶部添加一个if语句来检查xFile.Name包含“Failed”:

 For Each xFile In xFolder.Files If InStr(xFile.Name, "Failed") Then Application.ActiveSheet.Cells(rowIndex, 1).Formula = xFile.Name rowIndex = rowIndex + 1 End If Next xFile 

这样,您只能列出名称文本中包含“失败”的文件。