2014-03-19 88 views
0

使用下面的代碼,我從網上獲取,我可以在單個目錄中搜索包含特定行中的字符串的excel文件。我怎樣才能讓它在所有子文件夾中遞歸呢?我找到了一些答案,但我不明白我將如何在我的代碼中實現它們。我昨天才開始討論VBScript,我很困惑如何使這項工作。Excel在子文件夾中搜索

strComputer = "CAA-W74109188" 

Set objExcel = CreateObject("Excel.Application", strComputer) 

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 

Set FileList = objWMIService.ExecQuery _ 
("ASSOCIATORS OF {Win32_Directory.Name='c:\TDRS'} Where " _ 
    & "ResultClass = CIM_DataFile") 


For Each objFile In FileList 
    If (objFile.Extension = "xlsm" or objFile.Extension = "xls") Then 
    Set objWorkbook = objExcel.Workbooks.Open(objFile.Name) 
    Set objWorksheet = objWorkbook.Worksheets(1) 
    If objExcel.Cells(3,10) = "Complete" or objExcel.Cells(3,9) = "Released" Then 
     Wscript.Echo objFile.FileName 
    End If 

objExcel.DisplayAlerts = False 
objworkbook.Saved = False 
    objWorkbook.Close False 
End If 
Next 

objExcel.Quit 
+0

可能重複[如何遞歸地訪問一個文件夾內的文件子在VBScript?](http://stackoverflow.com/questions/14950475/how-to-recursively-access-subfolder-files-inside-一個文件夾在VBScript) –

回答

0

這是我用來刪除文件的腳本,我已經根據您的需要修改了這些腳本。遞歸函數是你完成工作所需要的,我總是發現它們很有趣,而且很難繞過我的腦海。

Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell") 
Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject") 
Dim objExcel : Set objExcel = CreateObject("Excel.Application") 

Dim Paths(0) 
Paths(0) = "c:\temp" 

For Each Path in Paths 
    FolderScan(Path) 
Next 

Sub FolderScan(Folder) 
Set base = oFSO.GetFolder(Folder) 
    If base.SubFolders.Count Then 
     For Each folder in Base.SubFolders 
     FolderScan(folder.Path) 
     Next 
    End If 
Set files = base.Files 
    If files.Count Then 
     For Each File in files 
      If LCase(oFSO.GetExtensionName(File.Path) = "xlsm") or _ 
      LCase(oFSO.GetExtensionName(File.Path) = "xls") Then 

       Dim objWorkbook : Set objWorkbook = objExcel.Workbooks.Open(File.Path) 
       Dim objWorkSheet : Set objWorkSheet = objWorkbook.Worksheets(1) 

       If (objExcel.Cells(3,10) = "Complete" or _ 
        objExcel.Cells(3,9) = "Released") Then 
        Wscript.echo File.Path 
       End if 
       objExcel.DisplayAlerts = False 
       objExcel.Quit 
      End If 
     Next 
    End If 
End Sub 
+0

這工作完美無瑕。非常感謝你。 – mc91

+0

嘿丹,你碰巧知道一種方式,我可以抑制宏運行時,當我的代碼打開並關閉Excel表?有一個「你想要保存」宏,它靠近運行,並打破了代碼。 – mc91

+0

試着在'Dim objExcel'行後面加上這一行 'objExcel.EnableEvents = False' –

0

這裏是一個迭代給定文件夾對象的所有文件和子文件夾的通用,遞歸函數。

Dim FileSystem 
Set FileSystem = CreateObject("Scripting.FileSystemObject") 

DoFolder FileSystem.GetFolder("c:\somefolder") 

Sub DoFolder(Folder) 

    Dim SubFolder 
    For Each SubFolder In Folder.SubFolders 
     DoFolder SubFolder 
    Next 

    Dim File 
    For Each File In Folder.Files 
     ' Operate on each file 
    Next 

End Sub