ファイルパスの取得(よく使うもの)

ファイルパスを取得する際に、よく使うものになります。
Windowsフォルダなどは、特殊フォルダのパスを取得を参照してください。

Sub GetFileNameSample()
    Dim in_filename As String
    Dim out_name As String
    Dim fnlist As Variant
    Dim idx As Long
    Dim fso As Scripting.FileSystemObject
    
    Set fso = New Scripting.FileSystemObject    ' オブジェクトの作成

    in_filename = "C:\ExcelVBA\ファイル\Test\0001\Sample.txt"


    ' ファイル名(パス、拡張子なし)の取得 (e.g. Sample)
    out_name = fso.GetBaseName(in_filename)
    MsgBox out_name

    ' 拡張子(.なし)の取得 (e.g. txt)
    out_name = fso.GetExtensionName(in_filename)
    MsgBox out_name

    ' ドライブの取得 (e.g. c:)
    out_name = fso.GetDriveName(in_filename)
    MsgBox out_name

    ' ファイルのパス (e.g. C:\ExcelVBA\ファイル\Test\0001)
    out_name = fso.GetParentFolderName(in_filename)
    MsgBox out_name

    ' \で分解したパス (e.g. "C:" "ExcelVBA" "ファイル" "Test" "0001" "Sample.txt")
    fnlist = Split(in_filename, "\")
    For idx = LBound(fnlist) To UBound(fnlist)
        MsgBox fnlist(idx)
    Next idx


    ' e.g. C:\ExcelVBA\ファイル\filepath.xlsm
    ' 実行しているExcelマクロのパス (e.g. C:\ExcelVBA\ファイル)
    MsgBox ThisWorkbook.Path

    ' 実行しているExcelマクロのファイル名 (e.g. filepath.xlsm)
    MsgBox ThisWorkbook.Name

End Sub

【補足】

Scripting.FileSystemObject を使用しています。
初期設定では、エラーが発生するので、参照設定「Microsoft Scripting Runtime」の設定が必要です。

コメント