VBA,在子文件夹中搜索

时间:2016-08-21 14:42:33

标签: vba ms-word word-vba

我正在查找.docx中特定文件的文件夹并想要打开它。我将X的名称放入Inputbox,转到Sheet Y,查看X的下一个右侧单元格并将其打开为Word(下一个单元格右边是我要打开的单词中的文件)。它正在工作,但问题是目标Word Doc可能在多个子文件夹中。有没有快速搜索这些子文件夹的方法?

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 个答案:

答案 0 :(得分:2)

我对搜索子文件夹的看法

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