繁体   English   中英

Excel VBA宏在.doc文件中查找文本

[英]Excel VBA macro find Text in .doc files

我想编写一个宏,可以在大约100个文件夹中找到名称为XXXX_TestSummary的文件,并在这些文件中搜索单词“Failed”。 宏应该返回包含文本或excel失败单词的文件名。

我被卡住了,因为我可以在文件夹中找到文件名。 下面是代码

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包含“失败”:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM