ファイル名からパスを取得する
 パスが不明な場合、FindSerachオブジェクトを使ってファイル名からパスを取得する
方法があります。

 FindSerachオブジェクトは、[ファイルを開く]ダイアログボックスの機能を表します。
 サンプルプロシージャでは、Cドライブの「TEST.txt」というファイルが存在する
パス名を全てイミディエイトウインドウに表示しています。

Sub Sample()

    Dim i, j, myFile, myFound As String

    myFile = "TEST.txt"
    With Application.FileSearch
        .NewSearch
        .LookIn = "C:\"
        .SearchSubFolders = True
        .Filename = myFile
        .MatchTextExactly = True
        .FileType = msoFileTypeAllFiles
        If .Execute() > 0 Then
            j = 0
            For i = 1 To .FoundFiles.Count
                myFound = .FoundFiles(i)
                If myFile = Name(myFound) Then
                    j = j + 1
                    Debug.Print i & ":" & _
                        Left$(myFound, Len(myFound) - Len(myFile))
                End If
            Next i
            MsgBox j & " 個のファイルが見つかりました。"
          Else
            MsgBox "対象ファイルはありませんでした"
        End If
    End With
    
End Sub

'---< Private:Function >-----
Private Function Name(s As String) As String

    Dim i As Integer, j As Integer

    i = 0
    Do
        j = i
        i = InStr(j + 1, s, "\")
    Loop Until i = 0
    If j <> 0 Then
        Name = Right(s, Len(s) - j)
      Else
        Name = s
    End If
    
End Function


 イミディエイトウィンドウには、次のように表示されます。

1:C:\Moug\
2:C:\Mougテクニック集\Excel\
3:C:\Projecta\
    ・
    ・
    ・

Excel97



戻る


Excel Word Access VBA! モーグ