2016-12-30 41 views
1

我想編寫一個宏,可以在大約100個文件夾中查找名稱爲XXXX_TestSummary的文件,並在這些文件中搜索單詞「Failed」。宏應返回文本或Excel中包含單詞失敗的文件名。Excel VBA宏在.doc文件中查找文本

我卡住了,因爲我只能找到文件夾中的文件名。以下是密碼

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 

請任何人都可以幫助解決這個問題嗎?

+0

你正在得到什麼錯誤?爲什麼你需要一個宏?這些文件夾是否在Excel中列出?這些的所有子文件夾和子文件夾等?你能更具體一點嗎? – dgorti

+0

我沒有收到任何錯誤,文件夾和子文件夾中的文件正在Excel中列出,但我無法找到.doc文件和搜索文檔中的失敗單詞並列出包含單詞失敗的文件名。 –

+0

請你能幫我修復這段代碼它非常重要嗎? –

回答

0

如果使用上面的代碼中去,你需要將你的循環中添加一些代碼:

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

,或者,你可以添加一個,如果實現這一循環的頂端語句來檢查,如果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 

這樣一來,你就只列出的名稱中包含文本「失敗」的文件。

+0

非常感謝您的幫助,但我需要找到微軟Word文檔中的失敗的單詞,所以現在我能夠找到具有名稱與_TESTSummary,但我需要訪問單詞文檔&找到單詞文檔失敗。你可以幫我嗎 ? –

+0

Word文檔有編輯限制或受保護的文檔2013.請幫助 –

+0

聽起來您需要使用Microsoft Word API。一旦你選擇你的文件,你會想創建一個Microsoft Word的實例(或使用現有的實例);那麼你將需要打開該文件並使用[Word](https://msdn.microsoft.com/EN-US/library/ff837519.aspx)API命令 –