2016-08-21 121 views
-1

我正在查找.docx中特定文件的文件夾,並且想要打開它。我將X的名稱放入Inputbox,轉到表單Y,查看X的下一個右側單元格,並將其作爲Word打開(下一個單元格右側是我想打開的單詞中的文件)。它正在工作,但問題是目標Word Doc可能在多個子文件夾中。有沒有快速的方法來搜索這些子文件夾?VBA,在子文件夾中搜索

Private Sub CommandButton1_Click() 
    On Error GoTo ErrorHandling 
    Application.ScreenUpdating = False 
    Dim AppWD As Object 
    Dim SearchX As String 
    Dim SearchArea As Range 
    Dim Y As String 
    Dim sPath As String 

    sPath = "C:\Users\VS\Desktop\test" 

    SearchRule = InputBox("X") 
    Set SearchArea = Sheets("Look").Range("A:A").Find(what:=SearchX, _ 
     LookIn:=xlFormulas, lookat:=xlWhole) 

    ActiveWindow.Visible = True 
    Target = SearchArea.Offset(0, 1).Value 
    Set AppWD = CreateObject("Word.Application") 
    AppWD.Visible = True 
    AppWD.documents.Open (sPath & "\" & Target & "." & "docx") 

    ErrorHandling: Exit Sub 
End Sub 

回答

1

我拿上搜索throught子

Sub searchSub() 
    Dim fso As FileSystemObject, fFile As File, fFolder As Folder 
    Dim fSubFolder As Folder, fPath As String, FileToSearch As String 

    Set fso = New FileSystemObject 
    FileToSearch = "SomeDocument.docx" 
    fPath = ThisWorkbook.Path 
    Set fFolder = fso.GetFolder(fPath) 

    For Each fFolder In fFolder.SubFolders 
      Set fSubFolder = fso.GetFolder(fFolder.Path) 

      For Each fFile In fSubFolder.Files 
       If fFile.Name = FileToSearch Then 
        'do something with file 
       End If 
      Next fFile 
    Next fFolder 
End Sub