2016-08-21 104 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