0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

VBAでフルパスからパスだけを取得する

Posted at

やりたいこと

フルパスの中から、ファイル名を除いたフォルダパスを取得します。

フルパスとは

C:¥Users¥yamada¥Documents¥test.txt のようなcドライブからファイルの場所までを表す文字列のことです。この処理では、C:¥Users¥yamada¥Documents¥test.txtから、test.txtだけを取り除きます。

Sub GetFolderPath()
    Dim FilePath As String 'String(文字列)型の変数「FilePath」を宣言
    Dim FolderPath As String 'String(文字列)型の変数「FolderPath」を宣言
    Dim i As Integer 'Integer(整数)型の変数「i」を宣言
    
    FilePath = Application.GetOpenFilename()  'ApplicationオブジェクトのGetOpenFilenameメソッドを使って、ファイルパスとファイル名を取得する    

    i = InStrRev(FilePath, "\") 
        'InStrRev関数は、ある文字列の中から指定した文字を最後の文字位置から検索し、最初に見つかった文字位置を返します。帰ってきた数値を変数「i」に格納します。
    FolderPath = Left(FilePath, i - 1) 'ファイルのフルパスの内、左から数えてi文字目まで取得する
    
    MsgBox FolderPath 'メッセージボックスに変数「FolderPath」に入っている文字列を表示する
    
End Sub

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?